Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are protected members allowed in final java classes?

Tags:

java

oop

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.

like image 719
Tom Tresansky Avatar asked Sep 07 '10 17:09

Tom Tresansky


People also ask

Why protected is used in Java?

The protected keyword is an access modifier used for attributes, methods and constructors, making them accessible in the same package and subclasses.

Why protected is not allowed in Java?

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.

What is the significance of using protected members in a superclass?

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).

What is protected final in Java?

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.


2 Answers

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.

like image 104
Tom Hawtin - tackline Avatar answered Oct 17 '22 02:10

Tom Hawtin - tackline


Because protected members can be accessed by other classes in the same package, as well as subclasses.

like image 21
skaffman Avatar answered Oct 17 '22 03:10

skaffman