Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

private final in superclass can be overridden?

Tags:

java

Which three statements are true? (Choose three.)

A. A final method in class X can be abstract if and only if X is abstract.

B. A protected method in class X can be overridden by any subclass of X.

C. A private static method can be called only within other static methods in class X.

D. A non-static public final method in class X can be overridden in any subclass of X.

E. A public static method in class X can be called by a subclass of X without explicitly referencing the class X.

F. A method with the same signature as a private final method in class X can be implemented in a subclass of X.

G. A protected method in class X can be overridden by a subclass of X only if the subclass is in the same package as X.

This question is from SCJP. Answer is BEF

I understand BE but F says that method is "private final" then how subclass can overide this method because its defined as final and private method.

Please clear F point.

like image 779
user2985842 Avatar asked Dec 06 '25 02:12

user2985842


2 Answers

Answer F isn't an example of overriding, it's an example of method scope. A method that is declared private in a class isn't visible to subclasses of that class, and so there's no overlap; the subclass doesn't see a method in the superclass that it can override. The subclass, with its own method void foo(int), is completely unaware of the superclass's private void foo(int).

like image 169
chrylis -cautiouslyoptimistic- Avatar answered Dec 08 '25 15:12

chrylis -cautiouslyoptimistic-


I understand BE but F says that method is "private final" then how subclass can overide this method because its defined as final and private method.

The question did not say anything about over-riding. Because a private method exists only in the context of that class, it does not participate in over-riding. You cannot over-ride a private method because private methods are not visible from outside of the class that defines them anyway.

Another way to look at is is that they are two unrelated methods and their signatures being identical is sheer coincidence.

Because a private method in a child-class is not over-riding a private method in a super class, the final keyword has no effect.

like image 23
Brandon Avatar answered Dec 08 '25 15:12

Brandon