Inheritance in Static Methods

后端 未结 5 434
南笙
南笙 2020-12-01 18:51

Why does the below code print \"Main\"?

public class Main
{
    public static void method()
    {
        System.out.println(\"Main\");
    }

    public sta         


        
5条回答
  •  时光取名叫无心
    2020-12-01 19:35

    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() or SubMain.method(). When you are calling m.method() java actually calls Main.method() because m is of type Main.

    If you want to enjoy polymorphism do not use static methods.

提交回复
热议问题