First, let's see what the following program will print:
Copy codeThe Code is as follows: class Dog {
Public static void bark (){
System. out. print ("woof ");
}
}
Class Basenji extends Dog {
Public static void bark (){}
}
Public class Bark {
Public static void main (String args []) {
Dog woofer = new Dog ();
Dog nipper = new Basenji ();
Woofer. bark ();
Nipper. bark ();
}
}
Take a look at it as if the program should print only one woof. After all, Basenji extends itself to Dog, and its bark method does not define why. The main method calls the bark method. The first is called on the Dog-type woofer, and the second is called on the Basenji-type nipper. The little basingi hiena won't call, but it is clear that this one will. If you run this program, you will find it prints woof. What's wrong with this poor guy?
The problem is that bark is a static method, and there is no dynamic dispatch mechanism for calling static methods [JLS 15.12.4.4]. When a program calls a static method, all the methods to be called are selected at the time of compilation, and this selection is made based on the modifier's compile-time type, the modifier's compile-time type is the name of the left part of the circle in the method call expression. In this case, the modifiers for the two method calls are the variables woofer And nipper, both of which are declared as the Dog type. Because they have the same compilation phase type, the compiler makes them call the same method: Dog. bark. This explains why the program prints out woof. Although the runtime type of the nipper is Basenji, the compiler only considers its compiler type.
To correct this program, you can directly remove the static modifier from the two bark method definitions. In this way, the bark method in Basenji will overwrite rather than hide the bark method in the Dog, and the program will print out woof instead of woof. Through overwriting, you can obtain dynamic distribution, but through hiding, you cannot obtain this feature.