问题
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
回答1:
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..
来源:https://stackoverflow.com/questions/6907549/why-cant-we-pass-a-instance-variable-to-the-super-class-constructor