什么是方法隐藏?

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()),调用的依然是父类中的静态方法,因为方法隐藏只在静态绑定时生效,不受动态绑定的影响。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值