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.

7
  • 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. Mar 4, 2012 at 7:51
  • can u explain me the difference between shadowing and overidding.
    – coder25
    Mar 4, 2012 at 8:24
  • @DavidHarkness Yes, that distinction is important to make clear. Mar 4, 2012 at 17:01
  • @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. Mar 4, 2012 at 17:07
  • 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. Mar 4, 2012 at 17:09
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.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.