java中方法隐藏不显示,隐藏在Java中的方法是什么?甚至JavaDoc的解释也令人困惑...

博客主要探讨Java中方法隐藏和重写的区别。通过代码示例展示,静态方法会发生隐藏,调用时取决于声明类型;实例方法具有多态性,会被重写,调用时取决于对象的运行时类型。还指出调用实例上的静态方法是不良实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

the version of the hidden method that gets invoked is the one in the superclass, and the version of the overridden method that gets invoked is the one in the subclass.

doesn't ring a bell to me. Any clear example showing the meaning of this will be highly appreciated.

解决方案

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");

}

}

Here, Cat.foo() is said to hide Animal.foo(). Hiding does not work like overriding, because static methods are not polymorphic. So the following will happen:

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

Calling static methods on instances rather than classes is a very bad practice, and should never be done.

Compare this with instance methods, which are polymorphic and are thus overridden. The method called depends on the concrete, runtime type of the object:

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");

}

}

Then the following will happen:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值