Suppose I have the following simple code:
class A {
protected int someMethod() {
return staticMethod();
}
private static int staticMethod() {
return 10;
}
}
class B extends A {
protected int someMethod() {
return super.someMethod();
}
public static int staticMethod() {
return 20;
}
}
class TestX {
private void main() {
B b = new B();
int finalValue =b.someMethod();
}
}
In the above code, when b.someMethod()
is executed, it ends up calling A
's version of staticMethod()
. But I thought static methods are called based on the type of reference of the main object. Since the object on which someMethod()
is called is of type B
, shouldn't B
's version of staticMethod()
be called even when A
's someMethod()
is called (because of the line return super.someMethod();
) ?
Given the above code, is there a way I can make B
's staticMethod()
get executed so that 20 is returned instead of 10 ?
I found a similar question but the idea suggested in it isn't relevant to me I think: