14

This answer shows Java's visibility modifiers and their meaning:

Modifier    | Class | Package | Subclass | World
————————————+———————+—————————+——————————+———————
public      |  y    |    y    |    y     |   y
————————————+———————+—————————+——————————+———————
protected   |  y    |    y    |    y     |   n
————————————+———————+—————————+——————————+———————
no modifier |  y    |    y    |    n     |   n
————————————+———————+—————————+——————————+———————
private     |  y    |    n    |    n     |   n

My question is, why does allowing visibility to all subclasses imply that you must give visibility to all other classes in your package? In other words, why did the Java creators make it like this, as opposed to:

Modifier    | Class | Subclass | Package | World
————————————+———————+—————————-+——————————+———————
public      |  y    |    y    |    y     |   y
————————————+———————+—————————+——————————+———————
no modifier |  y    |    y    |    y     |   n
————————————+———————+—————————+——————————+———————
protected   |  y    |    y    |    n     |   n
————————————+———————+—————————+——————————+———————
private     |  y    |    n    |    n     |   n
Community
  • 1
  • 1
morsecoder
  • 1,157
  • 1
  • 8
  • 22
  • 2
    See also: http://programmers.stackexchange.com/questions/205646/in-java-why-were-protected-members-made-accessible-to-classes-of-the-same-packa and http://programmers.stackexchange.com/questions/238581/why-is-there-no-subclasses-only-access-modifier-in-java – assylias Jun 17 '15 at 15:15
  • "...why did the Java creators make it like this", IMHO, nobody here can answer that. :) – Bhesh Gurung Jun 17 '15 at 15:23

2 Answers2

11

A package is supposedly written and maintained by the same team; it's ok to have looser access control within a package, assuming the programmer have an intimate knowledge of all the code.

A subclass is often written by someone else; a stricter constraint on API is better.

ZhongYu
  • 18,232
  • 5
  • 28
  • 55
1

Because the other way round like you suggest doesn't make sense in practice (which I admit isn't that obvious).

Suppose you have a package, containing a base class intended for extension by a client (third party, other team etc.), as well as other classes interacting with the base class (in the same package). Thats a pretty common case.

Now, your base class may contain members/methods intended only for use by the code supplied in the package, but that are intended to be inaccessible to the client extending the class.

Thats simple with package private (default) modifier as it is now, but it would be impossible if you switched the strength. You would lose the ability to hide things from your child classes while still making them available to your companions in the package.

Durandal
  • 19,415
  • 2
  • 32
  • 62