继承的类的静态成员变量是自身的时候为啥不爆StackOverflowError

有两个方面的问题:

1,当一个类B继承一个类C,而类B的一个实例又是类C的一个静态成员变量的时候,为什么不会报StackOverflowError,我知道类B的一个实例是类C的一个非静态成员变量的时候会报这个错误。虽然静态的只有一个实例,但引用还是是无限循环的啊?

 

2.当一个类B继承一个类C、一个接口A,类C中和接口A中都有一个相同的成员变量b的时候,分别因该怎么引用?(其中类C中的b是static的)

 

可能没有说的太清楚,我把代码贴出来了,求解答,困惑我很久了。。

public class InterfaceVariable {
    public static void main(String[] args) {
        B b = new B("class B");
//        System.out.println(b);
//        System.out.println(b.b);
//        System.out.println(B.b.b);
    }
}

interface A{
    B b = new B("interface A");
}

class C{
    static B b = new B("class C");
}

class B extends C implements A{
    public B(String s){
        System.out.println("class B's constractor,s="+s);
    }
}

 

 

 

蝴蝶不菲
浏览 657回答 3
3回答

撒科打诨

你想调用接口A的变量b吗?以下是代码: package headfirst.command.simpleremote; public class InterfaceVariable { public static void main(String[] args) { B b = new B("class B"); // System.out.println(b); // System.out.println(b.b); // System.out.println(B.b.b); } } interface A { B b = new B("interface A"); } class C { static B b = new B("class C"); } class B extends C implements A { public B(String s) { System.out.println("class B's constractor,s=" + s); System.out.println("interface A'b= " + A.b); } }

忽然笑

public B(String s){ super(); //默认调用的 System.out.println("class B's constractor,s="+s);创建B的对象会调用C的构造方法调用C的构造方法之前先要加载C ,创建静态对象B创建对象B 又调用C的构造方法,静态对象创建一次就可以了所以,C构造方法,B构造方法(静态对象B)然后C构造方法,B构造方法(main函数B)结束。

慕婉清6462132

索噶,明白了,多谢,
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java