java 隐藏 有什么用_Java中隐藏的方法是什么?甚至JavaDoc的解释也令人困惑

小编典典

public class Animal {

public static void foo() {

System.out.println("Animal");

}

}

public class Cat extends Animal {

public static void foo() { // hides Animal.foo()

System.out.println("Cat");

}

}

在这里,Cat.foo()据说藏起来了Animal.foo()。隐藏不像覆盖那样工作,因为静态方法不是多态的。因此,将发生以下情况:

Animal.foo(); // prints Animal

Cat.foo(); // prints Cat

Animal a = new Animal();

Animal b = new Cat();

Cat c = new Cat();

Animal d = null;

a.foo(); // should not be done. Prints Animal because the declared type of a is Animal

b.foo(); // should not be done. Prints Animal because the declared type of b is Animal

c.foo(); // should not be done. Prints Cat because the declared type of c is Cat

d.foo(); // should not be done. Prints Animal because the declared type of d is Animal

在实例而不是类上调用静态方法是一种非常糟糕的做法,绝不应该这样做。

将其与实例方法进行比较,实例方法是多态的,因此被覆盖。调用的方法取决于对象的具体运行时类型:

public class Animal {

public void foo() {

System.out.println("Animal");

}

}

public class Cat extends Animal {

public void foo() { // overrides Animal.foo()

System.out.println("Cat");

}

}

然后将发生以下情况:

Animal a = new Animal();

Animal b = new Cat();

Animal c = new Cat();

Animal d = null;

a.foo(); // prints Animal

b.foo(); // prints Cat

c.foo(); // prints Cat

d.foo(): // throws NullPointerException

2020-11-23

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值