java static 覆盖_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 中重写。

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值