Java Program using the default and parameterized constructor


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


Test() { 
   //statement
}

Test(int y) { 
   //statement
}

Example: How to implement default and parameterized constructor in java.

class Test {

    int x;

    Test() {
        x = 10;
    }

    Test(int y) {
        x = y;
    }

    void display() {
        System.out.println("The x value:" + 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:10
The x value:20