Reputation: 19892
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.
Upvotes: 20
Views: 6358
Reputation: 1
package p;
import java.sql.Connection;
public final class ProtectedTest {
String currentUser;
Connection con = null;
protected Object ProtectedMethod(){
return new Object();
}
public ProtectedTest(){
}
public ProtectedTest(String currentUser){
this.currentUser = currentUser;
}
}
package p;
public class CallProtectedTest {
public void CallProtectedTestMethod() {
System.out.println("CallProtectedTestMethod called :::::::::::::::::");
ProtectedTest p = new ProtectedTest();
Object obj = p.ProtectedMethod();
System.out.println("obj >>>>>>>>>>>>>>>>>>>>>>>"+obj);
}
}
package p1;
import p.CallProtectedTest;
public class CallProtectedTestFromp2 {
public void CallProtectedTestFromp2Method(){
CallProtectedTest cpt = new CallProtectedTest();
cpt.CallProtectedTestMethod();
}
public static void main(String[] args) {
CallProtectedTestFromp2 cptf2 = new CallProtectedTestFromp2();
cptf2.CallProtectedTestFromp2Method();
}
}
Upvotes: -1
Reputation: 147154
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.
Upvotes: 18
Reputation: 597046
The argument stated here that protected
members can be accessed by classes of the same package is valid, but in this case protected
becomes equal to the default visibility (package-private), and the question remains - why are both allowed.
I'd guess two things:
final
temporarily, until a design decision is made. One should not go and change all visibility modifiers each time he adds or removes final
Upvotes: 7
Reputation: 45433
You can argue that, but there's no real harm anyway. A non-final class may also have a protected member, but no subclass, it won't bother anybody either.
Upvotes: 0
Reputation: 47954
The protected modifier also allows access within the same package, not just to subclasses. So it's not completely meaningless on a final class.
Upvotes: 10
Reputation: 403451
Because protected members can be accessed by other classes in the same package, as well as subclasses.
Upvotes: 15