Search code examples
javainheritanceaccess-modifiers

how to declare a method in parent abstract class so that it can be accessed by children?


In Java, I have an abstract class with a method implemented (not abstract) which I want to be accessible by other classes which extend it, but not by everyone else in the package..

I think this is not possible, because private keeps it private, public and protected expose it too much..

How would you approach the problem? Reimplementing the same method in all the extended classes is out of discussion.. is there a way to access the parent methods?

thanks!


Solution

  • Use protected and make a package that contains only the abstract class and it's subclasses. Don't put any other classes in that package that shouldn't have access to protected methods.

    If your concern is that someone else might create a new class in that package and start accessing protected methods, there really isn't a language construct to prevent that. You have either trust your other developers or have a stringent peer review process.