Why protected can be access in same Package without inheritance in java?
14,396
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.
Related videos on Youtube
Author by
motaz99
Updated on September 15, 2022Comments
-
motaz99 almost 2 years
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
-
Jesper over 11 yearsBecause that's just how the Java programming language was designed.
-
Rohit Jain over 11 yearsJames Gosling has not yet joined SO. Wait till he registers. Then only you will get the exact reason.
-
Marko Topolnik over 11 yearsConsider 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 almost 8 years@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.
-
-
motaz99 over 11 yearsThank you <br>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