ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
### [名称隐藏](https://lingcoder.gitee.io/onjava8/#/book/08-Reuse?id=%e5%90%8d%e7%a7%b0%e9%9a%90%e8%97%8f) 如果 Java 基类的方法名多次重载,则在派生类中重新定义该方法名不会隐藏任何基类版本。不管方法是在这个级别定义的,还是在基类中定义的,重载都会起作用: ~~~ // reuse/Hide.java // (c)2017 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Overloading a base-class method name in a derived // class does not hide the base-class versions class Homer { char doh(char c) { System.out.println("doh(char)"); return 'd'; } float doh(float f) { System.out.println("doh(float)"); return 1.0f; } } class Milhouse {} class Bart extends Homer { void doh(Milhouse m) { System.out.println("doh(Milhouse)"); } } public class Hide { public static void main(String[] args) { Bart b = new Bart(); b.doh(1); b.doh('x'); b.doh(1.0f); b.doh(new Milhouse()); } } /* Output: doh(float) doh(char) doh(float) doh(Milhouse) */ ~~~ **Homer**的所有重载方法在**Bart**中都是可用的,尽管**Bart**引入了一种新的重载方法。在下一章中你将看到,使用与基类中完全相同的签名和返回类型覆盖相同名称的方法要常见得多。否则就会令人困惑。 你已经看到了Java 5 \*\*@Override \*\*注释,它不是关键字,但是可以像使用关键字一样使用它。当你打算重写一个方法时,你可以选择添加这个注释,如果你不小心用了重载而不是重写,编译器会产生一个错误消息: ~~~ // reuse/Lisa.java // (c)2017 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {WillNotCompile} class Lisa extends Homer { @Override void doh(Milhouse m) { System.out.println("doh(Milhouse)"); } } ~~~ **{WillNotCompile}**标记将该文件排除在本书的**Gradle**构建之外,但是如果你手工编译它,你将看到:方法不会覆盖超类中的方法,**@Override**注释防止你意外地重载。