What does the protected modifier mean? [closed]

心已入冬 提交于 2019-11-28 10:42:25
Jesper
  1. Yes, protected members can be accessed from the class itself, subclasses of the class and also all classes in the same package of the class (doesn't matter if those are subclasses or not). If you didn't know that last part before, then you've just learned something new.

  2. It simply means that you can use those members; if a member is not accessible, it means you'll get a compiler error when you try to use it.

Hussein Zawawi

In Java, protected means that the member can be accessed by any class in the same package and by subclasses even if they are in another packages.

Note

A protected variable is not visible outside the package

for example B extends A and A has a protected int x; it can be use within the class B. But cannot be access using its instance variable

1) Yes, protected members can be accessed by classes from the same package. That's the way Java works.

2) That means subclasses can access them.

I don't understand what does a protected member can also be accessed from ... mean, anyone can explain to me please?

For example, you have an object A and an object B, both of the same class. Object A will be able to query the protected properties and methods of object B if it has a reference to it. The protected modifier is enforced at class level, not at object level. This can come in handy in some situations.

arunram

Here are the answers

  1. Yes. Protected members (instance variables and methods) of a class can be accessed by other classes within the same package as well as by any other class that extends this class containing the member to be accessed. In the same specification, they have also given the table where the access level is strictly increasing providing all the accesses allowed in the preceding level: private -> package -> protected -> public

  2. As protected members (instance variables / states and methods / behaviors) of a class X are inherited and visible as part of the sub classes of X, say Y1, Y2, Y3 and may be further down to the next levels, any object references of type X or Y1, Y2, y3 can be used to access that protected member.

Just think of it as between public and private. You can access everything from public classes, and less from private classes.

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