简体   繁体   English

静态方法的继承和多态

[英]Static methods inheritance and polymorphism

How does inheritance and polymorphism work with static methods? 继承和多态如何与静态方法一起工作? Could someone explain what the proper output is supposed to be here and how it was derived? 有人可以解释这里应该有什么适当的输出以及它是如何得出的吗?

class A { public static int get() { return 17; } }
class B extends A { public static int get() { return 42; } }


 Main
 A x = new B();
 x.get();

The error message, 错误消息,

The static method get() from the type A should be accessed in a static way 类型A的静态方法get()应该以静态方式访问

I think I know how to access to it in a static way but this is a question from class and its sort of implied that one or the other values would be returned 我想我知道如何以静态方式访问它,但这是来自类的一个问题,其隐含着将返回一个或另一个值

In our program, we have the class definitions: 在我们的程序中,我们具有类定义:

class A { public static int get() { return 17; } }
class B extends A { public static int get() { return 42; } }

and somewhere else we declare A x = new B(); 在其他地方,我们声明A x = new B();

What number will the call x.get() return? 调用x.get()返回什么数字?

The invocation will return the int value 17 . 调用将返回int17

static methods are not inherited. static方法不会被继承。

static methods are bound and invoked based on the type of the expression they are invoked on. static方法根据调用它们的表达式的类型进行绑定和调用。

So 所以

x.get();

where x is of type A invokes A 's implementation. 其中xA类型调用A的实现。 Note also that static methods don't need an instance to be invoked. 还要注意, static方法不需要调用实例。

These would work as well. 这些也将起作用。

((A) null).get();
A.get();
...
public static A someMethod() {}
...
someMethod().get();

The message you got is a warning, not an error. 您收到的消息是警告,而不是错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM