Java Constructor

A constructor in Java is basically used to perform automatic initialization of an object. It has the same name as the name of the class to which it belongs.

Constructor’s syntax does not include a return type (not even void), since constructors never return a value.

A Java constructor cannot be abstract, static, final, and synchronized.

Constructors may include parameters of different types. When the constructor is invoked using the new operator, the types must match those that are specified in the constructor definition.

Java provides a default constructor which takes no parameter and performs no special action or initialization, when no explicit constructors are provided.

Constructor parameters provide us with a way to provide parameters for the initialization of an object.

 

Example

Below is an example of a cube class containing two constructors (one default and one parameterized constructor).

Cube.java

public class Cube {
    int length;
    int breadth;
    int height;

    public int getVolume() {
        return (length * breadth * height);
    }

    Cube() {
        length = 10;
        breadth = 10;
        height = 10;
    }

    Cube(int l, int b, int h) {
        length = l;
        breadth = b;
        height = h;
    }

    public static void main(String[] args) {
        Cube cube1, cube2;
        cube1 = new Cube();
        cube2 = new Cube(10, 20, 30);
        System.out.println("Volume of Cube1 is : " + cube1.getVolume() 
                + " square units.");
        System.out.println("Volume of Cube2 is : " + cube2.getVolume() 
                + " square units.");
    }

}

Output:

Volume of Cube1 is : 1000 square units.
Volume of Cube2 is : 6000 square units.

Note: If a class defines an explicit constructor, it no longer has a default constructor to set the state of the objects. If such a class requires a default constructor, its implementation must be provided. Any attempt to call the default constructor will be a compile time error if an explicit default constructor is not provided in such a case.

 

Difference between Constructor and Method

There are many differences between constructors and methods in Java. They are given below.

ConstructorMethod
1) A constructor is used to initialize the state of an object.1) A method is used to present the behavior of an object.
2) A constructor cannot have a return type.2) A method may have a return type.
3) A constructor is invoked implicitly.3) A method is invoked explicitly.

4) Java compiler provides a default constructor if we don’t have any.

4) Method is not provided by the compiler in any case.
5) Constructor name must be same as the class name.5) Method name may or may not be same as the class name.