gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 03:07:42 25 4
gpt4 key购买 nike

在下面的程序中,我覆盖了一个静态方法和一个实例方法,当我使用父类(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com