【发布时间】:2012-08-29 17:26:26
【问题描述】:
谁能解释一下这个程序的执行?
我知道extends 关键字的作用。但是我仍然无法弄清楚结果是什么以及为什么??
public class Maryland extends State {
Maryland() { /* null constructor */ }
public void printMe() { System.out.println("Read it."); }
public static void main(String[] args) {
Region mid = new State();
State md = new Maryland();
Object obj = new Place();
Place usa = new Region();
md.printMe();
mid.printMe();
((Place) obj).printMe();
obj = md;
((Maryland) obj).printMe();
obj = usa;
((Place) obj).printMe();
usa = md;
((Place) usa).printMe();
}
}
class State extends Region {
State() { /* null constructor */ }
public void printMe() { System.out.println("Ship it."); }
}
class Region extends Place {
Region() { /* null constructor */ }
public void printMe() { System.out.println("Box it."); }
}
class Place extends Object {
Place() { /* null constructor */ }
public void printMe() { System.out.println("Buy it."); }
}
【问题讨论】:
-
非常长且不可读的代码 sn-p,没有明显的努力来理解问题......
-
每个 Java 程序都必须从
main()开始。这段代码的第一行是做什么的?下一个呢?按照这个模式来弄清楚整个程序做了什么。如果您有难以理解的特定行,请随时回来具体询问。 -
@Code-Guru:程序以
main()开头。它在同一程序中使用多个类,其中main()函数位于Maryland()类中。 -
@xan 你知道我不是 OP,对吧?我的评论是对 OP 关于如何自己解决问题的提示。
标签: java inheritance