See the Java specification, the chapter 8.4.8. Inheritance, Overriding, and Hiding
https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.8
A class C inherits from its direct superclass all concrete methods m
(both static and instance) of the superclass for which all of the
following are true:
m is a member of the direct superclass of C.
m is public, protected, or declared with package access in the same
package as C.
No method declared in C has a signature that is a subsignature
(§8.4.2) of the signature of m.
.....
.....
8.4.8.1. Overriding (by Instance Methods)
- An instance method mC declared in or inherited by class C, overrides from C another method mA declared in class A, iff all of the following are true:
.....
- One of the following is true:
- mA is public.
- mA is protected.
- mA is declared with package access in the same package as C, .....
The above means, that you can't override a private method, and a class B actually doesn't override fun
.
If you either remove private
modifier or declare fun
as public or protected, then the code returns 5, because the fun
method becomes "overrideable".