MattWallace
MattWallace

Reputation: 1015

Is there good reason to access Java protected methods from non-subclasses?

The fact that protected methods can be accessed by classes that don't inherit from the defining class has always bothered me. I use abstract protected methods quite often in abstract classes to let subclasses define pieces of functionality. These are, in effect, private methods - they aren't intended be called outside of the class hierarchy. However, Java doesn't give me a way to say this, since protected methods can be called by any class in the package.

My question is, what is the design rationale for allowing this? Is there a valid use case for needing a method that can be called only in the package or by random subclasses outside of the package? I have never run into this case and I'm wondering if others have.

Upvotes: 1

Views: 285

Answers (2)

Alex
Alex

Reputation: 13941

It's quite common on large projects for test classes to call internal methods on the class under test, and protected or package-level access allows this.

In my opinion, the protected modifier is more of a documentation feature than an enforcement mechanism for encapsulation of code. By marking a method or field as protected, you're indicating to other developers that the code in question is an internal implementation detail subject to change in future versions, not a part of the public API for that class.

Through casting and reflection, other developers can often get at code that you didn't intend them to. If a method call is potentially harmful if called by other classes, the solution isn't to try and lock it down using Java's access rules. It's to refactor the class to favor immutable data structures and a clean separation of concerns.

Upvotes: 1

Eric Hydrick
Eric Hydrick

Reputation: 3527

The solution to this problem sounds like reorganizing your project to include multiple packages so that each package has superclasses, their subclasses, and nothing else. It's more of a workaround than a hard and fast solution, but it should do what you want it to do.

Upvotes: 0

Related Questions