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

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