Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we pass a instance variable to the super class constructor? [duplicate]

Tags:

java

scjp

Possible Duplicate:
Cannot refer to a instance method while explicitly invoking a constructor

I have been trying to do this for long time.

public class bb extends test {

    int t = 23;

    public bb() {
        super(t); //**This is the place that error comes**
        // TODO Auto-generated constructor stub
    }

    public bb(int v) {
    }
}

public class test {

    public test() {
        // TODO Auto-generated constructor stub
    }

    public test(int v) {
        // TODO Auto-generated constructor stub
    }
}

Controller class

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

        bb sd = new bb();
        System.out.println("sdfsdfsdfd");
    }
}

This is the error that comes. I want to know why a instance variable can't be passed to a super class constructor? I suspect that it's because there is no instance accessible to the constructor.

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot refer to an instance field t while explicitly invoking a constructor

like image 205
Chan Avatar asked Aug 20 '26 19:08

Chan


1 Answers

If you make that variable as a static variable that error will disappear.. this happens because

Instance Variables are created once its constructor is called but here in this case before the

child's constructor its parent Constructor gets executed.. which means instance variables/object of

child class doesn't exist in the Heap. or in other words they are not constructed yet.. but in case

of static variables they are first one's getting executed thus they have some values and that works

perfectly fine..

like image 129
ngesh Avatar answered Aug 23 '26 09:08

ngesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!