Java 类中可以覆盖静态方法吗?
发布日期:2021-05-09 03:48:46 浏览次数:22 分类:精选文章

本文共 1772 字,大约阅读时间需要 5 分钟。

作者:Yujiaao

Java 类中可以覆盖静态方法吗?

不,你不能在中覆盖静态方法,但在子类中声明一个完全相同的方法不是编译时错误,这称为隐藏在中的方法。

你不能覆盖中的静态方法,因为方法覆盖基于运行时的动态绑定,静态方法在编译时使用静态绑定进行绑定。

虽然可以在子类中声明一个具有相同名称和方法签名的方法,看起来可以在Java中覆盖静态方法,但实际上这是方法隐藏。

不会在运行时解析方法调用,并且根据用于调用静态方法的 Object 类型,将调用相应的方法。

这意味着如果你使用父类的类型来调用静态方法,那么原始静态将从父类中调用,另一方面如果你使用子类的类型来调用静态方法,则会调用来自子类的方法。,这篇推荐看下。

简而言之,你无法在中覆盖静态方法。如果你使用像Eclipse或Netbeans这样的Java IDE,它们将显示警告静态方法应该使用类名而不是使用对象来调用,因为静态方法不能在中重写。

/** * * Java program which demonstrate that we can not override static method in Java. * Had Static method can be overridden, with Super class type and sub class object * static method from sub class would be called in our example, which is not the case. */public class CanWeOverrideStaticMethod {    public static void main(String args[]) {        Screen scrn = new ColorScreen();        //if we can  override static , this should call method from Child class        scrn.show(); //IDE will show warning, static method should be called from classname    }}class Screen{    /*     * public static method which can not be overridden in Java     */    public static void show(){        System.out.printf("Static method from parent class");    }}class ColorScreen extends Screen{    /*     * static method of same name and method signature as existed in super     * class, this is not method overriding instead this is called     * method hiding in Java     */    public static void show(){        System.err.println("Overridden static method in Child Class in Java");    }}

输出:

Static method from parent class

此输出确认你无法覆盖  中的静态方法,并且静态方法基于类型信息而不是基于 Object 进行绑定。

如果要覆盖静态方法,则会调用子类或 ColorScreen 中的方法。这一切都在讨论中我们可以覆盖  中的静态方法。我们已经确认没有,我们不能覆盖静态方法,我们只能在中隐藏静态方法。

创建具有相同名称和方法签名的静态方法称为 隐藏方法。IDE 将显示警告:"静态方法应该使用类名而不是使用对象来调用", 因为静态方法不能在 Java 中重写。

推荐去我的博客阅读更多:

1.

2.

3.

4.

觉得不错,别忘了点赞+转发哦!

上一篇:Spring Boot 如何快速改造老项目?
下一篇:Dubbo 的心跳设计,值得学习!

发表评论

最新留言

不错!
[***.144.177.141]2025年04月19日 16时06分54秒