【发布时间】:2009-06-23 14:20:08
【问题描述】:
这是工作的java代码
class Cup {
public String sayColor() {
return "i have a color .";
}
}
class TCup extends Cup{
public String sayColor(){
System.out.println(super.getClass().getName());
return super.sayColor()+"color is tee green.";
}
}
class MyTCup extends TCup {
public String sayColor(){
System.out.println(super.getClass().getName());
return super.sayColor()+"but brushed to red now!";
}
}
class Test {
public static void main(String[] args) {
Cup c = new MyTCup();
System.out.print(c.sayColor());
}
}
并运行测试类打印
MyTCup
MyTCup
i have a color .color is tee green.but brushed to red now!
问题1: 在运行时,对象 C 的类型是 MyTCup,但它总是可以调用 super 方法。 MyTCup内的内存中是否有初始化对象后的方法栈,然后可以像代码一样在运行时调用?
问题2: 没有办法在其他对象中调用 super 方法。据我所知,c++ 可以随时转换为调用父方法。为什么它在 Java 中有所不同?
【问题讨论】:
-
对答案满意后,您应该接受它:)
标签: java overriding