Java覆盖实例和静态方法执行

标签 java inheritance

在下面的程序中,我覆盖了一个静态方法和一个实例方法,当我使用父类(super class)调用实例方法时,它正在执行子类方法,但在静态方法的情况下,它正在执行父类(super class)静态方法。这是为什么?

class Superclass
{
  public void print()
  {
    System.out.println("superclass print");
  }
  public static void staticPrint()
  {
    System.out.println("Superclass static print");
  }
}

public class Subclass extends Superclass
{   
  public static void staticPrint()
  {
    System.out.print("subclass staticPrint");
  }     
  public void print()
  {
    System.out.println("subclass print");
  } 
  public static void main(String... args)
  {
    Subclass subclass=new Subclass();
    Superclass superclass=subclass;
    superclass.staticPrint();
    superclass.print();
  }
}

输出:

Superclass static print
subclass print

最佳答案

静态方法不能覆盖,只能隐藏,至于变量。 看看here更多详情:

If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass hides the one in the superclass.

The distinction between hiding a static method and overriding an instance method has important implications:

The version of the overridden instance method that gets invoked is the one in the subclass. The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass.

关于Java覆盖实例和静态方法执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31247583/

相关文章:

java - 在java中使用多个定界符分割字符串

java - ListView 中的复选框

java - Spring MVC、RESTful 服务和 Apache Shiro 策略

java - 在 Java 中声明一个父类(super class)变量,然后用子类实例化它

windows - 进程优先级是否继承?

java - 减少条件运算符的数量

java - 平面文件数据库好用吗?

javascript - JS原型(prototype): Inheritance

python - 为什么父类要在 Python 中使用子类的实例?

C# 基类和 2 个派生类初始化