Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 225
Swaranga Sarma Avatar asked Feb 13 '11 21:02

Swaranga Sarma


People also ask

Is inheritance possible in static method?

Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor.

Are static methods inherited Java?

Static methods in Java are inherited, but can not be overridden. If you declare the same method in a subclass, you hide the superclass method instead of overriding it. Static methods are not polymorphic.

Are static methods inherited C++?

static member functions act the same as non-static member functions: They inherit into the derived class. If you redefine a static member, all the other overloaded functions in the base class are hidden.

Can static methods be overloaded and inherited?

Can we Override static methods in java? We can declare static methods with the same signature in the subclass, but it is not considered overriding as there won't be any run-time polymorphism. Hence the answer is 'No'.


3 Answers

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.

like image 140
porges Avatar answered Oct 06 '22 14:10

porges


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.

like image 15
AlexR Avatar answered Oct 06 '22 15:10

AlexR


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.

like image 2
developmentalinsanity Avatar answered Oct 06 '22 15:10

developmentalinsanity