Why are protected members allowed in final classes?
Shouldn't this be a compile-time error?
Edit: as people have pointed out, you can get same package access by using the default modifier instead. It should behave in exactly the same manner, because protected is just default + sub-classes, and the final modifier explicitly denies subclassing, so I think the answer is more than just to provide same package access.
The protected keyword is an access modifier used for attributes, methods and constructors, making them accessible in the same package and subclasses.
Since there is no way to restrict this class being subclassed by only few classes (we cannot restrict class being inherited by only few classes out of all the available classes in a package/outside of a package), there is no use of protected access specifiers for top level classes. Hence it is not allowed.
Using protected access offers an intermediate level of access between public and private. A superclass's protected members can be accessed by members of that superclass, by members of its subclasses and by members of other classes in the same package (i.e., protected members also have package access).
A protected method is inherited, and can be invoked from, a subclass. The way I see it, the design decision behind making a method both protected and final is: final, so the implementation cannot be changed, and protected, so that it cannot be called from anywhere outside the inheritance hierarchy.
The protected
modifier is necessary on methods that override protected
methods from a base class, without exposing those members to the public
.
In general, you could introduce a lot of unnecessary rules to outlaw implausible combinations (such as protected static
), but it wouldn't help much. You can't outlaw stupidity.
Because protected members can be accessed by other classes in the same package, as well as subclasses.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With