Why can't you have a protected abstract class in Java?

binarycreations picture binarycreations · Nov 17, 2011 · Viewed 10.9k times · Source

I have an abstract class which looks like:

abstract class AbstractFoo implements Bar {
  //Code goes here
}

However when I try to make AbstractFoo protected I get an error compile time error complaining that it is an illegal modifier.

protected abstract class AbstractFoo implements Bar {
  //Code goes here
}

Why can't you have a protected abstract class within Java?

EDIT: I should probably mention that this is not vanilla Java and is actually Blackberry / J2ME.

Answer

Jon Newmuis picture Jon Newmuis · Nov 17, 2011

As many others have noted, the restriction here has nothing to do with the fact that your class is abstract, but rather in the visibility modifier you have chosen to use. Keep in mind what each of these visibility modifiers means:

For the class in which you are using the keyword...

  • private: Only visible to this class

  • (default/package private): Only visible to this class and classes in its package

  • protected: Visible to this class, classes in its package, and subclasses of this class

  • public: Visible to any class

Top level classes cannot be declared private, because then nothing would ever be able to access them.

But your question stems around why they may not be declared protected. It is clear that a protected top-level class (were it able to exist) would be visible to itself (every class is visible to itself). It is also clear that a protected top-level class would be visible to classes in its package. However, making it visible to its subclasses is tricky. Which classes should be allowed to inherit our protected class?

If it is all of them, then our class might as well be public, because then we're saying that any class has the right to access our protected class. If it's none of them, then our class might as well be package-private, since only the other two conditions (being visible to itself and things in its package) are met. And it can't be "some of them," since we would need a way of defining which classes can access it, which is what the visibility modifier was for in the first place.

So for these reasons, top-level classes cannot be private or protected; they must be package-private or public.