dghtr
dghtr

Reputation: 581

regarding constructors

i was developing the below code....

class P {
    //public P(){}
    public P(int i) {

    }
}

class D extends P {
    public D(){ // default constructor must be defined in super class

    }
}

public class agf {      
    public static void main(String[] args) {

    }
}

Now in class p explicit parametrized constructor is defined and in class D default constructor is defined but it is still showing the compile time error ,please explain

Upvotes: 1

Views: 85

Answers (4)

Adi
Adi

Reputation: 717

When creating an instance of class D, the constructor of P is first called (since D is also P). The problem is that P's constructor cannot be called since a value has to be provided to it, and that's something you're not currently doing. To fix that, the first line in D's constructor have to be super(value), while value can be a parameter sent to D's constructor, or..anything else you want (in case you want to leave D's constructor a default one).

You can go through it step-by-step in debug, it can help to clear things out.

Upvotes: 0

Kalpak Gadre
Kalpak Gadre

Reputation: 6475

Your parent Class P explicitly defines a constructor, due to which no-arg constructor will not be added automatically. When you write a no-arg constructor for class D without having a specific constructor call for the class P using super keyword as mentioned below,

Class D extends P {
    public D() {
        super(10);        
    }
}

you are instructing it to call the no-arg constructor of P. Since P only has constructor that you defined, it cannot call the no-arg constructor of P.

In simple terms every object of D will have part of P. But it has no idea how to initialize / construct that P part, since it has no no-arg constructor.

Upvotes: 7

Jim Garrison
Jim Garrison

Reputation: 86744

In the subclass, if you don't invoke a superclass constructor explicitly, there must be a default superclass constructor that the VM can invoke for you.

In the superclass, if you explicitly define a constructor, the default no-argument constructor is NOT generated by the compiler.

Therefore, in the situation you show, you defined a non-default constructor in the superclass, which prevented the compiler from generating the default no-arg constructor. Then in the subclass, you didn't explicitly invoke a constructor in the superclass. The compiler tried to generate a no-arg superclass constructor call and didn't find a suitable constructor to call.

Upvotes: 1

MByD
MByD

Reputation: 137272

Inside this constructor:

public D()
{ 
    // no call to super?? implicit call to super()
}

There is an implicit call to the empty constructor of the super class (which doesn't exist in your case)

Either implement an empty constructor in the super class, or call the parameterized constructor explicitly, e.g.:

public D()
{ 
    super(1);
}

I would suggest you read this tutorial as well.

Upvotes: 1

Related Questions