Search code examples
javaoopconstructordefault-constructor

default constructor not invoked


Why :
If a class does not provide any constructors then default constructor(constructor without parameter) is given by the compiler at the time of compilation but if a class contains parameterized constructors then default constructor is not provided by the compiler.

I am compiling the code below.It gives compilation error.

Code :

class ConstructorTest
{
    // attributes
    private int l,b;

    // behaviour
    public void display()
    {
        System.out.println("length="+l);
        System.out.println("breadth="+b);
    }
    public int area()
    {
        return l*b;
    }

    // initialization
    public ConstructorTest(int x,int y) // Parameterized Constructor
    {
        l=x;
        b=y;
    }

    //main method
    public static void main(String arr[])
    {
        ConstructorTest r = new ConstructorTest(5,10);
        ConstructorTest s = new ConstructorTest();
        s.display();
        r.display();
        r.area();
    }
}

Console Error :

enter image description here

When I invoked only parameterized constructor. Its working fine.but when want to invoke the default constructor with parameterized constructor. Compiler gives compilation error as shown in picture.

Any immediate help will be highly appreciable. Thanks


Solution

  • The answer to your question is in the paragraph you provided:

    but if a class contains parameterized constructors then default constructor is not provided by the compiler.

    You have defined a parameterized constructor, therefore the default constructor is not provided by the compiler and therefore must be provided by yourself.