问题
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
回答1:
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.
来源:https://stackoverflow.com/questions/13309609/why-protected-can-be-access-in-same-package-without-inheritance-in-java