Learn Constructor In Java

Sharing is healthy !!

Hey guys!! how are you doing!!? In this post we are going to learn constructor in java.

what is a constructor?

Constructor is a member method which has the same name as class name.

NOTE:

  • constructor will never return value.
  • constructor is used to allocate memory to the object.
  • constructor is used to initialize values.
  • Even if you don’t define a constructor, java will create a default constructor whenever you create a class.
  • constructor is the first method which will be executed.

Also Read – Java Constructor Example

So let’s see an example,

public class Rectangle {
 
int width;
int height;
 
public int getArea(){
 
return (width * height);
 
}
 
public Rectangle() {
 
width = 3;
height = 4;
 
}
}
public class Constructor_Example {

public static void main(String[] args) {
 
Rectangle re = new Rectangle();
System.out.println(re.getArea());

}

}

Output:

12

In the above example i have declared two variables

int width;
int height;

so that we can calculate the area of rectangle using two variables. And then i have declared a method which will return int,

public int getArea(){
 
return (width * height);
 
}

above method will return the product of width into height. So this is the area of rectangle. In the next step we will initialize an instance of the class,

Rectangle re = new Rectangle();

Rectangle() with round brackets is called the constructor of Rectangle class.

And this is the most basic property of constructor, that is, even if you don’t define a constructor java will create a default constructor whenever you create a class.

Even if you have not created constructor method explicitly in the class above,  statement new Rectangle() is default constructor which is provided by java.

We can also define constructor like this,

public Rectangle() {
 
width = 3;
height = 4;
 
}
}

So this is the default constructor we have defined and in here we have defined the value of width and height so that if user don’t initialize width and height, java will initialize value for us using this default constructor.

Now we have initialized the instance of constructor and using this constructor we can call getArea() method,

System.out.println(re.getArea());

Above method will return product of width into height.


Learn Constructor In Java: constructor overloading

Constructor overloading is used whenever you want to provide some values by yourself. Here is example,

public class Rectangle {
 
int width;
int height;
 
public int getArea(){
 
return (width * height);
 
}

public Rectangle() {    // Default Constructor
 
width = 3;
height = 4;
 
}

public Rectangle(int w,int h) {   // Overloaded Constructor
 
width = w;
height = h;
 
}
}

Output:

12
1200
Sharing is healthy !!

Leave a Reply

Your email address will not be published.