Java Program using the default and parameterized constructor


In this program, You will learn how to implement default and parameterized constructor in Java.


Test() { }

Test(int y) { }


Example: How to implement default and parameterized constructor in Java

Run it Now
class Test {

    int x;

    Test() {
        x = 10;
    }

    Test(int y) {
        x = y;
    }

    void display() {
        System.out.println("The x value is :" + x);
    }

}

class Main {

    public static void main(String args[]) {
        Test t1 = new Test();
        t1.display();

        Test t2 = new Test(20);
        t2.display();
    }
}

Output:

The x value is :10
The x value is :20