静态方法中的继承 [英] Inheritance in Static Methods
本文介绍了静态方法中的继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么以下代码打印Main?
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");
}
}
在运行时, m
指向 Submain
的实例,因此它应该从概念上打印SubMain。
At runtime, m
is pointing to an instance of Submain
, so it should conceptually print "SubMain".
推荐答案
静态方法是在变量的编译时类型上解析的。 m
的类型为 Main
,因此 Main
中的方法被叫。
Static methods are resolved on the compile-time type of the variable. m
is of type Main
, so the method in Main
is called.
如果你把它改成 SubMain m ...
,那么<$ c $上的方法c>将调用SubMain 。
If you change it to SubMain m ...
, then the method on SubMain
will be called.
这篇关于静态方法中的继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文