如何理解Java中子类和父类存在同名静态函数?

577 阅读1分钟

我们先来看一个问题:

在父类中含有static修饰的静态方法,那么子类在继承父类以后可不可以重写父类中的静态方法呢?

答案是不能。

在解释这个答案之前,我们先看代码:

class Parent {
    public static void m4() {
        System.out.println("parent m4");
    }
}
​
class Child extends Parent{
    public static void m4() {
        System.out.println("child m4");
    }
}
public static void main(String[] args) {
    new Parent().m4();
    new Child().m4();
}

上面这段代码执行的输出是

parent m4
child m4

看到这里,我们就会感到疑惑,子类Child不是重写了父类Parent的静态方法吗?为什么上面问题的答案是不能。

我们再看一段代码

public static void main(String[] args) {
    Parent parent = new Child();
    parent.m4();
}

输出结果为

parent m4

可能有些人会疑惑为什么输出结果是parent m4而不是child m4

我们看下上面方法编译后的结果

public static void main(String[] args) {
    Parent parent = new Child();
    Parent.m4();
}

这是因为类成员是属于类的。尽管我们可以通过对象去调用静态方法,但是编译之后还是使用类名去访问静态方法。

因此,对于Java中子类和父类存在同名静态函数的理解为:如果父类有一个静态方法,且子类也有一个返回类型、方法名、参数列表都与之相同的静态方法,在子类中只是对父类的该同名方法进行隐藏,而不是重写。 父类和子类含有的其实是两个没有关系的方法,两者之间并不具有多态性。