2

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?

2
  • As Sotirios noted, A x = new B(); will return 17 on x.get(); but B y = new B(); will return 42 on y.get(); Commented Apr 11, 2014 at 3:09
  • You can get some special software, that will tell you the output of any Java program. It's perfect for solving questions like this. You just give it your program, and you can find out what the output of the program is. I seriously recommend using this software for this type of question - it will save you lots of time. You can find out the answer for yourself, instead of having to trust people whom you've never met. And in case you're wondering what this amazing software is called ... it's "Java". Try it. Commented Apr 11, 2014 at 3:20

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.