栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 AnimalCat.foo(); // prints CatAnimal 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 Animalb.foo(); // should not be done. Prints Animal because the declared type of b is Animalc.foo(); // should not be done. Prints Cat because the declared type of c is Catd.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 Animalb.foo(); // prints Catc.foo(); // prints Catd.foo(): // throws NullPointerException


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/596259.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号