在Java中,静态方法不能被覆盖。原因在这里整齐地解释
因此,它不依赖于它所引用的对象。但相反,这取决于引用的类型。因此,静态方法被称为隐藏另一个静态方法而不覆盖它。
例如(Cat 是 Animal 的子类):
public class Animal {
public static void hide() {
System.out.format("The hide method in Animal.%n");
}
public void override() {
System.out.format("The override method in Animal.%n");
}
}
public class Cat extends Animal {
public static void hide() {
System.out.format("The hide method in Cat.%n");
}
public void override() {
System.out.format("The override method in Cat.%n");
}
}
主类:
public static void main(String[] args) {
Cat myCat = new Cat();
System.out.println("Create a Cat instance ...");
myCat.hide();
Cat.hide();
myCat.override();
Animal myAnimal = myCat;
System.out.println("\nCast the Cat instance to Animal...");
Animal.hide();
myAnimal.override();
Animal myAnimal1 = new Animal();
System.out.println("\nCreate an Animal instance....");
Animal.hide();
myAnimal.override();
}
现在,输出将如下所示
Create a Cat instance ...
The hide method in Cat.
The hide method in Cat.
The override method in Cat.
Cast the Cat instance to Animal...
The hide method in Animal.
The override method in Cat.
Create an Animal instance....
The hide method in Animal.
The override method in Animal.
对于 ,运行时系统调用在调用该方法的引用的编译时类型中定义的方法。class methods
换句话说,对静态方法的调用在编译时映射,并且取决于引用的声明类型(在本例中为父级),而不是运行时引用点的实例。在此示例中,的编译时类型为 。因此,运行时系统调用 中定义的隐藏方法。myAnimal
Animal
Animal