views:

130

answers:

3

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 he very nature of the subclass, private, and/or protected.

Does something like this exist in Java?

+1  A: 

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

Bill the Lizard
+4  A: 

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.

coobird
This is unfortunate. :(
+1  A: 

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.

CPerkins