我有以下代码。
public class Parent {
@Override
public int hashCode() {
return 0;
}
}
public class Child extends Parent {
public void test() {
this.toString();
this.hashCode();
}
}
正如您在上面的代码中看到的,Child 从 Object 继承 toString(),从 Parent 继承 hashCode()。Child#test 的字节码操作如下。
ALOAD 0: this
INVOKEVIRTUAL Object.toString() : String
ALOAD 0: this
INVOKEVIRTUAL Child.hashCode() : int
RETURN
我认为如果invokevirtual 调用Object.toString(),它应该调用Parent.hashCode() 以保持一致性。或者,调用 Child.hashCode(),然后调用 Child.toString()。
但是,当且仅当目标方法被 Object 继承时,invokevirtual 才保持其一致性。
只有在这种情况下,invokevirtual 才会调用 Object 中的方法。对于其他情况,invokevirtual 调用当前类中的方法。
我想知道为什么会这样。