Constructors in Java

Constructor in Java is similar to a method but does not have a return type. A constructor is called when object of the class is created. The following program shows a constructor ConstructorProgram(). It is called when object obj is created.

package com.company;

public class ConstructorProgram {
    int x = 3;

    public ConstructorProgram() {
        System.out.println(x);
    }

    public static void main(String[] args) {
        ConstructorProgram obj = new ConstructorProgram();
    }

}

Output:

3

The following program shows constructor with parameters. Here parameters are integer x and integer y and arguments 3 and 5 are passed into the constructor.

package com.company;

public class ConstructorProgram {
    int x , y;

    public ConstructorProgram(int x, int y) {
        System.out.println("The value of integer x is "+x);
        System.out.println("The value of integer y is "+y);
    }

    public static void main(String[] args) {
        ConstructorProgram obj = new ConstructorProgram(3,5);
    }
}

Output:

The value of integer x is 3
The value of integer y is 5

In a program if a constructor is not created then a constructor is created by default. This is called the default constructor. The following program shows a default constructor. Here there is no constructor and the program outputs default values on execution.

package com.company;

public class ConstructorProgram {
    int x ;
    float y;
    boolean a;

    public static void main(String[] args) {

        ConstructorProgram obj = new ConstructorProgram();

        System.out.println("The value of integer x is "+ obj.x);
        System.out.println("The value of integer y is "+ obj.y);
        System.out.println("The value of integer a is "+ obj.a);
    }
}

Output:

The value of integer x is 0
The value of integer y is 0.0
The value of integer a is false
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments