欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > java >内容正文

java

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

发布时间:2025/3/21 java 34 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Java 类中可以覆盖静态方法吗? 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

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

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

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

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

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

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

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

/**  *  * 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

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

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

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

作者:Yujiaao
https://segmentfault.com/a/1190000019962661

总结

以上是生活随笔为你收集整理的Java 类中可以覆盖静态方法吗?的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。