静态方法中的继承
为什么下面的代码打印“Main”?
public class Main
{
public static void method()
{
System.out.println("Main");
}
public static void main(String[] args)
{
Main m = new SubMain();
m.method();
}
}
class SubMain extends Main
{
public static void method()
{
System.out.println("SubMain");
}
}
在运行时,m
指向 Submain
的实例,因此它在概念上应该打印“SubMain”。
Why does the below code print "Main"?
public class Main
{
public static void method()
{
System.out.println("Main");
}
public static void main(String[] args)
{
Main m = new SubMain();
m.method();
}
}
class SubMain extends Main
{
public static void method()
{
System.out.println("SubMain");
}
}
At runtime, m
is pointing to an instance of Submain
, so it should conceptually print "SubMain".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
静态方法根据变量的编译时类型进行解析。
m
的类型为Main
,因此调用Main
中的方法。如果将其更改为
SubMain m ...
,则将调用SubMain
上的方法。Static methods are resolved on the compile-time type of the variable.
m
is of typeMain
, so the method inMain
is called.If you change it to
SubMain m ...
, then the method onSubMain
will be called.这是因为静态方法不是多态的。此外,静态方法不应由对象调用,而应使用类来调用,即
Main.method()
或SubMain.method()
。当你调用
m.method()
时,java实际上调用了Main.method()
,因为m是Main类型。如果您想享受多态性,请不要使用静态方法。
It is because static methods are not polymorphic. Moreover static method should be invoked not by object but using the class, i.e.
Main.method()
orSubMain.method()
.When you are calling
m.method()
java actually callsMain.method()
because m is of type Main.If you want to enjoy polymorphism do not use static methods.
当我尝试执行此类操作时,Eclipse 会向我发出此类警告:
静态方法不参与继承。该变量的类型为
Main
,因此编译器将您的函数调用解析为Main.method()
。为了增加乐趣,请尝试将
m
设置为null
。Eclipse gives me this sort of warning when I try to do this sort of thing:
Static methods do not take part in inheritance. The variable is of type
Main
, so the compiler resolved your function call toMain.method()
.For added fun, try setting
m
tonull
.Java 对静态方法执行早期绑定,这与动态绑定的实例方法不同。
因为您的对象变量是 Main 类型,所以调用在编译时绑定到超类实现。
一个很好的解释可以在这里找到。
Java performs early binding for static methods, unlike instance methods which are dynamically bound.
Because your object variable is of type Main the call is bound to the superclass implementation at compile time.
A good explanation is available here.
静态方法与其类名静态绑定,因为 m 是 Main 类的类型
然后编译后它看起来像下面
Main.method();
编译完你的课程后
运行以下命令
javap -c 主要
你可以看到Main类的jvm汇编代码
你会看到以下内容
m.method //调用静态
invoke static ,invokespecial 告诉静态绑定
invoke特殊,invoke接口告诉动态绑定
static methods are statically binded with their class name because m is type of Main class
then after compilation it would look like as following
Main.method();
after compilation of your class
run the following command
javap -c Main
u can see the jvm assembly code for Main class
and u would see following
m.method //invoke static
invoke static ,invoke special tells that static binding
invoke special,invoke interface tells that dynamic binding