简体   繁体   English

静态方法中的继承

[英]Inheritance in Static Methods

Why does the below code print "Main"? 为什么下面的代码显示“ 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". 在运行时, m指向Submain的实例,因此它在概念上应打印“ SubMain”。

Static methods are resolved on the compile-time type of the variable. 静态方法在变量的编译时类型上解析。 m is of type Main , so the method in Main is called. mMain类型的,因此调用Main的方法。

If you change it to SubMain m ... , then the method on SubMain will be called. 如果将其更改为SubMain m ... ,则将调用SubMain上的方法。

It is because static methods are not polymorphic. 这是因为静态方法不是多态的。 Moreover static method should be invoked not by object but using the class, ie Main.method() or SubMain.method() . 此外,静态方法不应由对象调用,而应使用类Main.method()SubMain.method()来调用。 When you are calling m.method() java actually calls Main.method() because m is of type Main. 当您调用m.method() java实际上会调用Main.method()因为m是Main类型。

If you want to enjoy polymorphism do not use static methods. 如果您想享受多态性,请不要使用静态方法。

Eclipse gives me this sort of warning when I try to do this sort of thing: 当我尝试执行此类操作时,Eclipse会向我发出此类警告:

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

Static methods do not take part in inheritance. 静态方法不参与继承。 The variable is of type Main , so the compiler resolved your function call to Main.method() . 该变量的类型为Main ,因此编译器将您的函数调用解析为Main.method()

For added fun, try setting m to null . 为了增添乐趣,请尝试将m设置为null

Java performs early binding for static methods, unlike instance methods which are dynamically bound. Java对静态方法执行早期绑定,这与动态绑定的实例方法不同。

Because your object variable is of type Main the call is bound to the superclass implementation at compile time. 因为您的对象变量的类型为Main,所以在编译时将调用绑定到超类实现。

A good explanation is available here . 这里有一个很好的解释。

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(); 静态方法与它们的类名称静态绑定,因为m是Main类的类型,然后在编译后,其外观类似于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 在编译您的类之后,运行以下命令javap -c Main您可以看到Main类的jvm汇编代码,并且您会看到以下m.method // //调用static invoke static,调用special表示静态绑定调用special,invoke接口告诉动态绑定

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

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