黑马程序员技术交流社区
标题:
这个两个的输出又是什么?有奖回答
[打印本页]
作者:
hejinzhong
时间:
2014-9-8 10:59
标题:
这个两个的输出又是什么?有奖回答
本帖最后由 hejinzhong 于 2014-9-8 11:08 编辑
http://bbs.itheima.com/thread-142116-1-1.html
参考上一个帖子
//分别运行父类和子类中的main方法
public class Parent {
public void init(){
System.out.println("1.parent");
this.Demo();
}
public static void Demo(){
System.out.println("2.parent");
}
public static void main(String[] args) {
Parent parent = new Son();
parent.init();
}
}
----------------------------------------------------------------------------------------
public class Son extends Parent {
public void init(){
super.init();
System.out.println("3.son");
this.Demo();
}
public static void Demo(){
System.out.println("4.son");
}
public static void main(String[] args) {
Son son = new Son();
son.init();
}
}
还是老规矩,解释的清澈前三有黑马币!
复制代码
作者:
孤鸢
时间:
2014-9-8 14:52
本帖最后由 孤鸢 于 2014-9-8 15:04 编辑
上线竟然得到了黑马币,很激动呀,正缺黑马币,跟到这个帖,给楼主捧捧场,也算对得起楼主的黑马币吧:lol
这题给demo()加了static修饰,还是考多态中子父类的成员特性。多态中,成员变量和静态方法都是跟所在类静态绑定的,只有非静态方法是动态绑定。涉及到多态,程序运行时总是参考子类对象,因此从这可以判定不管运行哪个main方法,结果是一样的。
接下来就是输出是什么的问题,因为demo()变成了静态方法,因此在调用的时候就是参考引用所在类,父类this指的是parent,子类this指的是son,最后结果
1.parent
2.parent
3.son
4.son
作者:
daoqin
时间:
2014-9-9 12:06
运行第一个就是多态问题,通过基类指针访问子类方法,
所以不管运行哪个,执行顺序不变。
1.parent
2.parent
3.son
4.son
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2