0

I have the following class:

public class X {
    public void A() {
        B();
    }

    private static void B() {
        System.out.println("111111111");
    }
}

Now I have the following inherited class Z:

public class Z extends X {

    private static void B() {
        System.out.println("22222222");
    }
}

now if I do

Z myClass = new Z();
Z.A();

I will get: 111111111 as a result. (Also, eclipse tells me that B() in the inherited class is never called).

Why? And how can I run the inherited B method?

martijnn2008
  • 3,552
  • 5
  • 30
  • 40
dsb
  • 2,347
  • 5
  • 26
  • 43
  • 5
    static methods are not called polymorphically. They are statically bound at compilation time. Use an instance method. And don't make it private either: private methods are private, and thus can't be overridden. https://docs.oracle.com/javase/tutorial/java/IandI/override.html – JB Nizet Nov 01 '15 at 12:35

4 Answers4

1

The B methods are static. When you call the method A it uses the implementation of class B (because that's where the method A is defined). Class B is not aware of the existence of class Z and cannot call a method of class Z.

Because the method is static, it's not overridden upon inheriting from B. Polymorphism only works with instances of a class. Static method does not play the polymorphism game and cannot be overridden.

Avi
  • 21,182
  • 26
  • 82
  • 121
  • That was what I afraid of. Thanks for the explanation. – dsb Nov 01 '15 at 12:51
  • 1
    It's also not overridden because the method is `private`. A private method is not even seen in a subclass, so it can't ever be overridden. If you give it a different access modifier, then the fact that it is also `static` comes into play. – Erwin Bolwidt Nov 01 '15 at 13:10
1

Change access modifier of method from private static to protected

If you re-define base class non-static & non-private method in derived class, it's called overriding.

If you re-define base class static method in derived class, it's called method hiding or method shadowing.

You have done hiding rather overriding in your example.

Have a look at this SE Question

Community
  • 1
  • 1
Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
0

You're calling X's inherited A method, and this calls its private B method.

private methods and attributes are not inherited.

Julen
  • 1,024
  • 1
  • 13
  • 29
0

It looks like you are overriding method B() in class Z but method B() is not overridden here. Since B() is static so class A and class Z has there own method B(). Scope of all the Static methods and variables are class level not an object level.

KP_JavaDev
  • 222
  • 2
  • 4
  • 11