java - 为什么在Java中无需继承就可以在同一个包中访问protected?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13309609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why protected can be access in same Package without inheritance in java?
提问by motaz99
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
请帮助我了解Java中protected的具体工作
回答by Jesper
Why? Because that's how the Java programming language was designed. There's not much more to it.
为什么?因为这就是 Java 编程语言的设计方式。没有更多了。
Something that is protected
is accessible from
protected
可以访问的东西
- 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.
这与 C++ 不同,但 Java 不是 C++,因此它不一定以相同的方式工作。