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 al

  • 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
Media content

Code Snippet

// 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 App {
    public static void main(String args[]) {
        RectangleShape o1 = new RectangleShape();

        System.out.println("Area of Rectangle : " + o1.area());
    }
}