Base父类代码如下
public class Base {
public static String showme(){
return "Base";
}
public void print(){
System.out.println(showme());
}
}
Sub子类代码如下
public class Sub extends Base {
public static String showme(){
return "Sub";
}
}
main函数如下
public class AppMain {
public static void main(String args[]){
Base base=new Sub();
base.print();
Sub sub=new Sub();
sub.print();
}
}
打印结果两个都为Base
请问怎样解释在print方法中showme()方法的调用与什么有关?
For static methods, the invokestatic instruction is used. The invokestatic instruction does not require an instance reference as an operand, but only the symbol reference of the static method. Therefore, the static method has been specified at compile time, and part of the bytecode of the print method :
As you can see, invokestatic has specified that Base.showme is called, so how you call the print method will not change the behavior of invokestatic.
In addition, I feel that the questioner has a wrong understanding of static binding and dynamic binding. I suggest that the questioner refer to this question: Java, calling polymorphic methods in the constructor
Subclasses can inherit the static properties and static methods of the parent class, but they cannot override static methods.
If there is a method label in the subclass that has the same method label as the parent class (same method name, same parameter type, same return value type, and even the same access level), it can only mean that a new method has been created for the subclass that is the same as the parent class. A static method with the same name as the class, rather than an override of the static method of the parent class.
As @kylewang pointed out the print method part bytecode
The method call is clearly specified as Base.showme()