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?

1
  • 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. docs.oracle.com/javase/tutorial/java/IandI/override.html Commented Nov 1, 2015 at 12:35

4 Answers 4

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.

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

2 Comments

That was what I afraid of. Thanks for the explanation.
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.
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

Comments

0

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

private methods and attributes are not inherited.

3 Comments

Thank you very much. I changes it from private to protected but still the same behaviour. Any idea why?
That's not the reason. The reason is that the method is static.
@Avi Actually it is very much the reason, just as the fact that it is static is the reason.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.