官方文档是这样写的:
Class methods
If a subclass defines a class method with the same signature as a class method in
the superclass, the method in the subclass hides the one in the superclass.
如果一个子类定义了一个和父类静态方法中相同的方法(即方法名,参数和返回类型相同),
则该类隐藏了父类中的这个方法。
The distinction between hiding and overriding has important implications. The
version of the overridden method that gets invoked is the one in the subclass. The
version of the hidden method that gets invoked depends on whether it is invoked
from the superclass or the subclass
而该隐藏的静态方法是否被调用,取决于是父类(引用)还是子类(引用)调用了该静态方法
以下是一个例子:- public class Test2
- {
- public static void main(String[] args)
- {
-
- //需要注意的是,这里跟以往的父类引用指向子类对象有点不用
-
- //这个子类创建的对象是由子类类型“N”引用的,所以调用output方法将输出“N”
-
- N n = new N();
- n.output();
-
- //这个子类创建的对象是由父类类型“M”引用的,所以调用output方法将输出“M”
- M m = new N();
- m.output();
- }
-
- }
- class M
- {
- public static void output()
- {
- System.out.println("M");
- }
- }
- class N extends M
- {
- public static void output()
- {
- System.out.println("N");
- }
- }
复制代码 |