Swaranga Sarma
Swaranga Sarma

Reputation: 13433

Inheritance in Static Methods

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".

Upvotes: 11

Views: 13774

Answers (5)

Anoop Singhal
Anoop Singhal

Reputation: 43

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

Upvotes: 0

mmccomb
mmccomb

Reputation: 13817

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.

Upvotes: 2

AlexR
AlexR

Reputation: 115388

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.

Upvotes: 15

developmentalinsanity
developmentalinsanity

Reputation: 6249

Eclipse gives me this sort of warning when I try to do this sort of thing:

The static method XXX() from the type XXX should be accessed in a static way

Static methods do not take part in inheritance. The variable is of type Main, so the compiler resolved your function call to Main.method().

For added fun, try setting m to null.

Upvotes: 2

porges
porges

Reputation: 30590

Static methods are resolved on the compile-time type of the variable. m is of type Main, so the method in Main is called.

If you change it to SubMain m ..., then the method on SubMain will be called.

Upvotes: 20

Related Questions