【发布时间】:2018-01-09 14:44:43
【问题描述】:
我看到了一些与此类似的早期问题,但我正在寻找更具体的答案。
1) 在这种情况下,JVM 如何/何时执行动态绑定?
我尝试使用超类引用变量
superobj调用派生类方法derivedFunc1()。它失败了(我的失败假设:编译器说成员derivedFunc1()不属于为超类引用变量分配(或限制)的内存。)我尝试使用超类引用变量
superobj调用方法superFunc1()。尽管在超类中有superFunc1(),但它“以某种方式”从派生类调用superFunc1()。 (这与我的假设相矛盾,因为访问超出了其受限的内存范围)。
所以我的问题:
1) superobj 如何能够访问派生类成员 superFunc1() 但不能访问另一个派生类成员 derivedFunc1()。
2) 谁/什么要求 JVM 执行动态绑定?
import java.util.*;
import java.text.*;
public class MyLocale {
public static void main(String[] args) {
MySuper superobj=new MyDerived();
superobj.derivedFunc1(); //Statment1: fails because it cannot call functions from derived class. (Okay I understand this part)
superobj.superFunc1(); //Statment2: has 2 options (one in super, one in derived) to call from and here it calls derived function.
}
}
class MySuper {
void superFunc1() {
System.out.println("Super");
}
}
class MyDerived extends MySuper{
void derivedFunc1() {
System.out.println("Derived");
}
void superFunc1() {
System.out.println("Derived");
}
}
【问题讨论】:
-
你应该阅读这篇文章docs.oracle.com/javase/tutorial/java/IandI/subclasses.html 并修正你的术语,以便清楚你在问什么。试着坚持“方法”,不要在没有明确说明发生了什么的情况下说“它失败了”之类的话,并澄清你希望你的班级拥有的关系。例如,“超类”和“基类”是同义词。
标签: java dynamic-binding