user3363135 user3363135 - 7 months ago 21
Java Question

Static methods inheritance and polymorphism

How does inheritance and polymorphism work with static methods? Could someone explain what the proper output is supposed to be here and how it was derived?

class A { public static int get() { return 17; } }
class B extends A { public static int get() { return 42; } }


Main
A x = new B();
x.get();


The error message,


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


I think I know how to access to it in a static way but this is a question from class and its sort of implied that one or the other values would be returned

In our program, we have the class definitions:

class A { public static int get() { return 17; } }
class B extends A { public static int get() { return 42; } }


and somewhere else we declare
A x = new B();


What number will the call
x.get()
return?

Answer

The invocation will return the int value 17.

static methods are not inherited.

static methods are bound and invoked based on the type of the expression they are invoked on.

So

x.get();

where x is of type A invokes A's implementation. Note also that static methods don't need an instance to be invoked.

These would work as well.

((A) null).get();
A.get();
...
public static A someMethod() {}
...
someMethod().get();

The message you got is a warning, not an error.