Constructor in Java


Constructors are special methods named after the class and without a return type, and are used to construct objects. Constructors, like methods, can take input parameters. Constructors are used to initialize objects. Abstract classes can have constructors also.

Constructors are different from methods:

  • Constructors can only take the modifiers public, private, and protected, and cannot be declared abstract, final, static, or synchronized.
  • Constructors do not have a return type
  • Constructors MUST be named the same as the class name.

Types of constructor :

  • Default constructor
  • Parametrized constructor
  • Copy constructor
  • Constructor Overloading

This Java program demonstrates the usage of constructors in a class to initialize the instance variables of an object when it is created.

  • The program defines a class RectangleShape with instance variables length and width, and a default constructor. The constructor is called when an object of the class is created using the new operator. In this case, the constructor sets the values of length and width to 2 and 10, respectively.
  • The area method calculates the area of a rectangle using the length and width instance variables and returns the result.
  • In the main method, an instance of the RectangleShape class is created using the new operator. This calls the default constructor of the class and initializes the instance variables length and width to 2 and 10, respectively. The area method is then called on the object to calculate the area of the rectangle.

Source Code

//Constructor in Java
class RectangleShape {
    int length, width;
 
    public RectangleShape() {
        System.out.println("Constructor Called");
        length=2;
        width=10;
    }
 
    int area() {
        int a = length * width;
        return a;
    }
}
 
public class constructor {
    public static void main(String args[]) {
        RectangleShape o1 = new RectangleShape();
        System.out.println("Area of Rectangle : " + o1.area());
 
    }
}
 

Output

Constructor Called
Area of Rectangle : 20
To download raw file Click Here

Basic Programs