首页 新闻 会员 周边

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

0
[已解决问题] 解决于 2014-04-20 10:57

有两个方面的问题:

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);
    }
}

 

 

 

苍枫露雨的主页 苍枫露雨 | 小虾三级 | 园豆:1027
提问于:2014-03-22 15:39
< >
分享
最佳答案
1

你想调用接口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);
    }
}
奖励园豆:5
beyondchina | 小虾三级 |园豆:680 | 2014-04-14 14:56

没法通过b去调用,是吗?

苍枫露雨 | 园豆:1027 (小虾三级) | 2014-04-17 22:39

@苍枫露雨: 当然可以啊,不过变量名不能一样,要不它怎么知道要调用哪个类或者接口。

package headfirst.command.simpleremote;

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

    }
}

interface A {
    B b1 = 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.b1);
    }
}
beyondchina | 园豆:680 (小虾三级) | 2014-04-19 09:28

@beyondchina: 恩,了解了,3ks ~~

苍枫露雨 | 园豆:1027 (小虾三级) | 2014-04-20 10:57
其他回答(1)
1
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)
结束。


hisoka | 园豆:224 (菜鸟二级) | 2014-04-12 17:32

索噶,明白了,多谢,

支持(0) 反对(0) 苍枫露雨 | 园豆:1027 (小虾三级) | 2014-04-17 22:34
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册