所以我收到作业后说我只答对了 15/30 分,但没有解释我错了哪道题或为什么错了。我即将参加考试,我想在参加考试之前弄清楚这一点。因此,我希望有人能帮助我理解我的对/错是什么?为什么?
这是我的作业:
考虑以下 Java 程序:
public class Base {
public void m(Object o) { System.out.println("Base.m(Object)"); }
public static void m(String s) { System.out.println("Base.m(String)"); }
public void m(Class c) { System.out.println("Base.m(Class)"); }
}
public class Derived extends Base {
public void m(Object o) { System.out.println("Derived.m(Object)"); }
public static void m(String s) { System.out.println("Derived.m(String)"); }
public static void main(String[] args) {
Base b = new Derived();
b.m(new Object());
b.m(new Integer(5));
b.m("Hello");
b.m(b.getClass());
}
}
问题1(5分):Derived.main()中b的静态类型是什么?
我的答案:基础
问题2(5分):Derived.main()中b的动态类型是什么?
我的答案:派生
问题 3(20 分):我们的 Derived 虚表中正确排序的条目是什么 翻译?请使用classname.methodname(typenames)”表示法。 另外,请忽略第一个条目,即 __isa。
我的答案:Derived 的 vtable-
- 派生.m(对象)
- Base.m(类)
我的印象是 Base.m(String s) 和 Derived.m(String s) 都是静态方法;因此它们不会被包含在 vtable 中。另外,我假设将使用 Derived.m(Object) 而不是 Base.m(Object),因此不会包含在 Derived 的 Vtable 中。
最佳答案
Question 1 (5 Points): What is the Static Type of b in Derived.main()?
正确:静态类型始终是声明的类型,在本例中为 Base:Base b = new Derived();
Question 2 (5 Points): What is the Dynamic type of b in Derived.main()?
正确:动态类型是变量指向的类型,在本例中为派生
Question 3 (20 Points): What are the correctly ordered entries in Derived’s vtable for our translator? Please use classname.methodname(typenames)” notation. Also, ignore the first entry, which is __isa.
- Derived.m(Object) 覆盖 Base.m(Object):Derived.m(Object)> 正确
- Base.m(c 类)重载 Derived.m(对象):Base.m(c 类) 正确
如果要考虑静态方法:
- Derived.m(String s) 将影子 Base.m(String s)。当方法被隐藏时,该方法纯粹依赖于静态类型;在这种情况下,静态类型是 Base,因此将调用
Base.m(String s)
;
这是一个奇怪的例子:
Derived a = null;
a.m("World");
这会打印 Derived.m(String)
,为什么? a
的动态类型为 null,但 Derived.m(String)
只关心 a
的静态类型 Derived
关于java - 需要澄清静态/动态类型和 Vtable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8513378/