Java: Access modifier more restrictive than 'protected', less restrictive than 'private'?
-
06-07-2019 - |
Question
I want something similar to protected
, where only a class which implements the protected
field and anything that subclasses it can access it.
So, I want to be able to declare a variable in the base class as private
, but still be able to access it from a subclass.
Perhaps this is against the very nature of subclassing, private
, and/or protected
.
Does something like this exist in Java?
Solution
There are only four access levels for fields in Java:
private
- package-private (default; no access modifier)
protected
public
protected
will allow subclasses, other classes in the same package, and members in the class itself to access the protected
member.
The short answer is, there is no way to achieve exactly what is desired.
For a description of those four access modifiers, Controlling Access to Members of a Class from The Java Tutorials has more specific information.
OTHER TIPS
If you control the codebase, you can always control what goes into the package with the baseclass - if it's alone in its package, only subclasses can access the member you want to keep private except for subclasses.
No, there's no access modifier to do exactly that. The protected
modifier is the closest thing, but that exposes the field to any class in the same package as well as to subclasses (in or out of the same package).
Not possible. U can still declare your variables as private then declare public methods that modify the variables in the superclass. You then call the public method on the variable.