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

百般思念 提交于 2019-12-24 09:39:37

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!