0

I have a question I hope you can help me with:

I have an abstract class that contains some utility abstract methods, but I want these methods to be restricted only to subclasses, I obviously can't use a private modifier, but protected is not enough because in the same package there are also classes that don't extend it, but they can use these methods if the extended ones are instantiated in them:

What can I do? Thanks!

Dea5
  • 131
  • 1
  • 9

1 Answers1

2

You can't do it. The only way is to rearrange your package structure in a way, that only the base class and its children were inside the package. To achive this, you may move all the classes that aren't children into a subpackage - they won't see protected methods.

Out of curiosity - why do you need this? The only reason that comes to my mind is to prevent programmers error, because malicious code may access these methods using reflection anyway.

ekaerovets
  • 1,158
  • 10
  • 18
  • I see, but why? I mean, why does Java not support a thing like this? – Dea5 May 20 '17 at 22:03
  • @Dea5 I believe, that would make the language unnecessary complicated. Following this logic, we may have ten access modifiers as well - e.g. restrict access to the current package / to the current package and subpackages / to the subclasses and superclasses only etc. – ekaerovets May 20 '17 at 22:05
  • Seems reasonable... thanks for your answer! – Dea5 May 20 '17 at 22:06
  • @Dea5 by the way, some people think there should be modifier library, which means that the method may be called from the same library (e.g. kotlin's module). Would be useful – ekaerovets May 20 '17 at 22:08
  • "you may move all the classes that aren't children into a subpackage" Yes but not necessarily. Using a different package is enough. – davidxxx May 20 '17 at 22:10
  • [Curiosity edit] I simply like a "clean code", and the thought that those methods could be called outside their "space" triggers me, ha! – Dea5 May 20 '17 at 22:13
  • The assumption is that code inside the same package can be trusted not to do anything bad. – Louis Wasserman May 20 '17 at 22:29