17
  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


  public class a {
  protected int x;
  }

  public class b {
        b() {
              a A=new a();
              A.x=9;//why we can access this field ?
        }
  }

please help my to know the specific work of protected in Java

aioobe
  • 413,195
  • 112
  • 811
  • 826
motaz99
  • 471
  • 3
  • 8
  • 15
  • please help me to know the specific work of protected in Java – motaz99 Nov 09 '12 at 14:09
  • See here: http://stackoverflow.com/questions/215497/in-java-whats-the-difference-between-public-default-protected-and-private – looper Nov 09 '12 at 14:11
  • 8
    Because that's just how the Java programming language was designed. – Jesper Nov 09 '12 at 14:11
  • 2
    James Gosling has not yet joined SO. Wait till he registers. Then only you will get the exact reason. – Rohit Jain Nov 09 '12 at 14:18
  • 1
    Consider this: if it **didn't** work that way, how would you make a set of tightly coupled classes in the same package, that also exported some of their internals to outside subclasses? You'd need even more modifiers for that, making the language unnecessarily complex. – Marko Topolnik Nov 09 '12 at 14:27
  • On Programmers: http://programmers.stackexchange.com/questions/205646/in-java-why-were-protected-members-made-accessible-to-classes-of-the-same-packa – Ciro Santilli OurBigBook.com Feb 11 '15 at 13:54
  • @MarkoTopolnik, came here to say just that. You should really elaborate and post it as an answer. The only alternative as I see it would have been to have private < protected < default < public. But presumably it's not a good idea to expose members to subclasses by default. – aioobe Aug 08 '16 at 08:08
  • 2
    @aioobe The main point for me is that both "public" and "protected" signal public API -- some parts of API are designed to be used by extending library's classes. Seen this way, it would be really bad if you couldn't export something to your package "friends" without it becoming public API. – Marko Topolnik Aug 08 '16 at 10:10
  • Yep. That's another good point. – aioobe Aug 08 '16 at 10:26

1 Answers1

18

Why? Because that's how the Java programming language was designed. There's not much more to it.

Something that is protected is accessible from

  • the class itself,
  • classes in the same package (doesn't matter if they are subclasses or not),
  • subclasses (doesn't matter if they are in the same package or not).

This is different from C++, but Java is not C++, so it doesn't necessarily work in the same way.

Jesper
  • 202,709
  • 46
  • 318
  • 350
  • 1
    Thank you
    So in Java if we have on packet we can't let subclasses access spacial field and prevent other classes in same packet to access it
    – motaz99 Nov 09 '12 at 14:28