这是工作的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 中有所不同?