0

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:

Calling subclass's static method from parent class

Community
  • 1
  • 1
Ahmad
  • 12,886
  • 30
  • 93
  • 146
  • I don't think there's any typo. Can you copy paste the line on which you think there's a typo ? – Ahmad Jul 12 '16 at 18:16
  • [Your other question](http://stackoverflow.com/questions/38334849/subclasss-static-method-not-being-called-from-parent-classs-non-static-method) got closed as duplicate, no reason to just recreate the same question., – tkausl Jul 12 '16 at 18:17
  • @tkausl, this question is different from my last one. If you read, I'm asking a different thing here. I would appreciate if you can re-open my question. – Ahmad Jul 12 '16 at 18:20
  • @AndrewTobilko That won't be enough. The super implementation of `someMethod` is trying to invoke the `static` method. That wouldn't compile. – Sotirios Delimanolis Jul 12 '16 at 18:23
  • @SotiriosDelimanolis, it will be enough, someMethod is accessible by both this and super references in the child, isn't it? – Andrew Tobilko Jul 12 '16 at 18:28
  • 1
    @AndrewTobilko Sorry, I misread. Their intention is to get 20. Whether you remove the hiding method in the subclass or not, they'll still get 10. – Sotirios Delimanolis Jul 12 '16 at 18:30

0 Answers0