Why protected can be access in same Package without inheritance in java? [duplicate]

老子叫甜甜 提交于 2019-11-29 17:09:46

问题


  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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!