This discussion is archived
1 Reply Latest reply: Mar 2, 2013 7:43 AM by EJP RSS

Java bytecode operation 'invokevirtual' does not keep consistency

994388 Newbie
Currently Being Moderated
I have following codes.

public class Parent {

@Override
public int hashCode() {
return 0;
}

}

public class Child extends Parent {

public void test() {
this.toString();
this.hashCode();
}

}
As you see in the above codes, Child inherits toString() from Object and hashCode() from Parent. Bytecode operation of Child#test is as following.

ALOAD 0: this
INVOKEVIRTUAL Object.toString() : String
ALOAD 0: this
INVOKEVIRTUAL Child.hashCode() : int
RETURN

I think if invokevirtual calls Object.toString(), it should call Parent.hashCode() for consistency. or, Child.hashCode() called, then Child.toString() should be called.

However, invokevirtual does not keep its consistency if and only if target method is inherited by Object.

Only that case, invokevirtual calls method in the Object. For other cases, invokevirtual calls method in current class.

I want to know why this happens.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points