我可以覆盖和重载 Java 中的静态方法吗? [英] Can I override and overload static methods in Java?

查看:25
本文介绍了我可以覆盖和重载 Java 中的静态方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道:

  1. 为什么不能在 Java 中覆盖静态方法?
  2. 静态方法可以在 Java 中重载吗?

推荐答案

静态方法不能被完全覆盖,但可以隐藏父静态方法

Static methods can not be overridden in the exact sense of the word, but they can hide parent static methods

实际上,这意味着编译器将在编译时决定执行哪个方法,而不是在运行时决定执行哪个方法,就像重写的实例方法一样.

In practice it means that the compiler will decide which method to execute at the compile time, and not at the runtime, as it does with overridden instance methods.

一个简洁的例子看看这里.

这个是解释<强>覆盖实例方法和隐藏类(静态)方法.

And this is java documentation explaining the difference between overriding instance methods and hiding class (static) methods.

覆盖:Java 中的覆盖仅意味着将根据对象的运行时类型调用特定方法,并且不是它的编译时类型(这是覆盖的情况)静态方法)

Overriding: Overriding in Java simply means that the particular method would be called based on the run time type of the object and not on the compile time type of it (which is the case with overriden static methods)

隐藏:静态的父类方法不是子类的一部分(尽管它们是可访问的),因此不存在覆盖它.即使您在子类中添加另一个静态方法,与其父类相同,此子类静态方法是唯一的,区别于其父类中的静态方法.

Hiding: Parent class methods that are static are not part of a child class (although they are accessible), so there is no question of overriding it. Even if you add another static method in a subclass, identical to the one in its parent class, this subclass static method is unique and distinct from the static method in its parent class.

这篇关于我可以覆盖和重载 Java 中的静态方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆