您的位置:首页 > 编程语言 > Java开发

java继承类相互引用加上静态属性的困扰

2008-05-23 16:14 267 查看
在网上看到这样一段代码


class father




...{


public String var="father";


public static String staticvar="staticfather";


void method()




...{


System.out.println("father method");


}


static void staticmethod()




...{


System.out.println("father staticmethod");


}


}


class son extends father




...{


public String var="son";


public static String staticvar="staticson";


void method()




...{


System.out.println("son method");


}


static void staticmethod()




...{


System.out.println("son staticmethod");


}


}


class goodClass




...{


public static void test()




...{


father f=new son();


System.out.println("f.var="+f.var);


System.out.println("f.staticvar="+f.staticvar);


f.method();


f.staticmethod();


}




}




public class Inherit ...{






/** *//**


* @param args


*/




public static void main(String[] args) ...{


// TODO Auto-generated method stub


goodClass.test();


}




}



结果是:


f.var=father


f.staticvar=staticfather


son method


father staticmethod

如果去掉属性的static, 结果是不变的

如果给method加上static属性,结果如下


f.var=father


f.staticvar=staticfather


father method ;;已经改变


father staticmethod

如果测试时用


son f = (son)new father();

编译没问题,但执行时会报cast exception

单步测试结果, 在

father f=new son();

下断点

启动eclipse debug模式, 注意按F5, 即step into
看看整个流程

执行如下:


father : public static String staticvar="staticfather";
son: public static String staticvar="staticson";
son: 构造函数 //这里没有
father: 构造函数
构建this指针: 此时debug 的 variables窗口 this下两个var, 此时为null
father: public String var="father"; // 赋值给this第一个var
son : public String var="son"; // 复制给this第二个var
this 指针 赋给 f

完成此句

两个var, 调用f.var的时候取得是第一个, "father"
static属性是全局的,这个不受 f 控制

method不是static就会根据new 后面的对象来指向函数.

再往下有待继续学习.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐