Scope of protected members

2019-02-25 21:36发布

Iam preparing for SCJP , also i came to know that protected members scope is within the package as well as in other package with some conditions like possible only with inheritance.

For example : i have three classes as Parentclass Childclass Friendclass

package x.parent;

 class Parentclass{
 protected int x=10;
  ...............
  }

 package x.child;

 class Childlass extends Parentclass{
  super.x=20;
  ...............
}

 package x.child;

 import x.parent.Parentclass;

 class Friendclass{
 Parentclass pc = new Parentclass();
 pc.x=30;
  ...............
}

Whats the reason behind that, in Friendclass the member x will not accept to assign a value to that, behaves as private member not in case of Childclass.

2条回答
仙女界的扛把子
2楼-- · 2019-02-25 22:00

There are four access modifiers

private - just this class
no modifier - just this class or this package (NOT subclass)
protected - just this class, this package, or subclass
public - everyone and their cousin

Since it uses the default modifier, it has access if one of the following is true:

  1. Is part of the class itself (Nope!)
  2. Is part of the package of the class itself (Nope!)

So it fails the criteria, and so you don't get access.

查看更多
一夜七次
3楼-- · 2019-02-25 22:16

You can't even access Parentclass.x in Childclass because x has default visibility (not protected). See http://download.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

edit:

x.child.Friendclass is not in the same package as x.parent.Parentclass. x.child.Friendclass does not inherit from x.parent.Parentclass.

as TotalFrickinRockstarFromMars's summary states and the Java access control docs also state, this means that Friendclass is not allowed to access the field x.

查看更多
登录 后发表回答