Java子父类中静态方法

Java中的静态方法只能继承,不能重写!!

官方文档是这样写的:

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


上述例子中如果N类中的output方法没有static修饰,则会报不能重写的编译错,所以static可以这样来解释:加上static是隐藏了父类中的方法,而不是重写。

同样的,如果父类中的方法不是静态的,那么子类中的同名方法也不可以是静态的,也就是说静态的方法不能被覆盖,静态的方法也不能覆盖非静态的,总之一句话:静态的都不能覆盖,要么全静态,要么全非静态。

原文地址:https://www.cnblogs.com/dongye/p/3411115.html