3
class X1 { private final void show() { ... } } class X2 extends X1 { private final void show() { ... } } 

Question 1

The code is compiling without any errors. Since the final keyword prevents methods from being overidden, why does the code compile?

Question 2

If I remove the private keyword from both show methods, the code doesn't compile as expected. Why?

2

2 Answers 2

11

In X2, the method is not the same method, it's shadowing the method in X1. Since the method in X1 is private, X2 has no awareness of it and thus is able to reuse the method signature. So, when you have an X2 object and you call show, it will use X2's show. When you have an X1 object, it will use X1's show.

If you used the @Override annotation on X2, it would give a warning that the method to be overridden doesn't exist (or error, not 100% sure).

This is obviously not a good idea to use the same method signature as someone looking at it later could get very confused and it definitely doesn't make clear your intentions.

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

7 Comments

Since they are private, they can only be called from other methods in X1 and X2. The type of the object doesn't matter but rather the context where it is called. Other methods on X1 that call show on an instance of X2 will call X1.show.
can u explain me the difference between shadowing and overidding.
@DavidHarkness Yes, that distinction is important to make clear.
@prerna I'm not sure what more you want me to say. Overriding means that the functionality of the super class method is subsumed by the functionality of the subclass method. So, wherever show is used when using an X2, it should use the X2 show. Shadowing means means that the subclass method only works on X2 methods that call show and the X1 show will work only on X1 methods that call show.
If this seems confusing, this should tell you why it's best to avoid shadowing unless you have some really good reason for it. Using the @Override annotation will either verify that you're overriding what you expect or alert you that something is amiss.
|
1

As they are private functions, each function belongs its own class. The show method in X2 is not overriding the one X1 as its private. X2 is not aware of the show method in X1. But when you remove the private classifier, X2 awares of and compiling complains.

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.