Constructors

Constructors

Objects that are created must be given initial values. The first approach uses the dot operator to access the instance variables and then assign values to them individually. It would be too lengthy to initialize all the variables of all the objects.

The second approach is to take the help of a method like getdata to initialize each object individually using the statements like

Rect1.getdata(15,10);

 

Constructor enables an object to initialize itself when it is created. Constructors have the same name as the class itself. Constructor do not specify return type, not even void. This is because they return instance of the class itself.

 

Let us consider the example to illustrate constructor.

Class rectangle

{

Int length;

Int width;

Rectangle(intx, int y ) // constructor method

{

Length = x;

Width = y;

}

Intrextarea()

{

Return(length x width );

}

}

Class rectanglearea

{

Public static void main(string args[]);

{

Rectangle rect1 = new rectangle(15,10); // calling constructor

Int area1 = rect1.rectarea();

System.out.println(“Area = “ +area1);

}

 

}

 

Leave Comment

Important Topics

Title
OOPS
Data Types
JAVA
JVM
Command Line Args
Machine Neutral
Scope of Variables
Operators :
Generic Type Casting
IF Else
Switch Statement
The while statement
The do statement
The for statement
Classes, objects and methods
Constructors
Methods Overloading
Static Members
Nesting of methods
Inheritance : Extending a Class
Overriding methods
Overriding methods
Final variable and methods
Abstract class in Java
Visibility control