Krishnan Mishra Krishnan Mishra - 8 months ago 50
Java Question

Why the parameterised constructor of the super class is not called in the following code?

class demo1
{
demo1(int x){
System.out.println("This is super class constructor!");
}
}

public class demo extends demo1
{
int y;
demo()//or if i do: demo(int y)
{
super(y);
System.out.print(4);
}
public static void main(String args[]){
demo d = new demo();
}


Following is the error showing up

demo.java:13: error: cannot reference y before supertype constructor has been called
super(y);
^
1 error

Answer Source

The sub-class instance variable y is only initialized after the super class constructor is called. Therefore it can't be referenced in the call to the super class constructor.

Even if it was allowed, the super(y); call would make no sense in your example, since it is not passing any meaningful data to the super class constructor (since you didn't assign anything to the y member). It only makes sense to pass to the super class constructor arguments that were passed to the sub-class constructor, or constant values.

For example, the following will pass compilation:

public class Demo extends Demo1
{
    int y;
    Demo (int y) {
        super(y); // here y is the argument passed to the Demo constructor, not the
                  // instance variable of the same name
        System.out.print(4);
    }
    public static void main(String args[]) {
        Demo d = new Demo(10);
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download