Java中的方法隐藏:指在子类中定义一个静态方法,该子类的属性或者方法名与父类中的相同,即在子类中调用这个方法时,会优先调用子类中的方法,而不是父类中的方法,此时父类中的方法或属性被隐藏(父类的属性或方法只是形式上不见了,实际还存在)
注意:要隐藏父类的静态方法,子类的静态方法必须与父类同名,同参类型,用返回类型
方法隐藏的例子:
class Parent {
public static void hello() {
System.out.println("Hello from parent");
}
}
class Child extends Parent {
public static void hello() {
System.out.println("Hello from child");
}
}
public class MethodHidingExample {
public static void main(String[] args) {
Parent parent = new Parent();
parent.hello(); // 输出:Hello from parent
Child child = new Child();
child.hello(); // 输出:Hello from child
Parent childAsParent = new Child();
childAsParent.hello(); // 输出:Hello from parent
}
}
在上述示例中,Parent
类中定义了一个名为 hello
的静态方法。Child
类继承自 Parent
并隐藏了 hello
方法。
在 main
方法中,我们分别创建了 Parent
和 Child
的实例,并调用它们的 hello
方法。当调用 parent.hello()
时,输出为 "Hello from parent",因为这是从父类中的静态方法调用的结果。而当调用 child.hello()
时,输出为 "Hello from child",因为这是从子类中的隐藏方法调用的结果。
需要注意的是,当使用父类的引用指向子类的对象时(如 Parent childAsParent = new Child()
),调用的依然是父类中的静态方法,因为方法隐藏只在静态绑定时生效,不受动态绑定的影响。