首先对于Java中的protected访问控制符,具有如下属性
- protected 访问控制符能被用于方法和成员变量
- 声明为protected的方法和成员变量能被同一个包里的所有类所访问,就像默认修饰符package一样
- 能被该类的子类所访问,子类可以和父类不在一个包中。
- 另一个包中的子类只能通过子类或其子类的引用来访问父类中受保护的成员。同一包中的子类没有此限制。这样可以确保来自其他包的类只访问属于其继承层次结构一部分的成员。
在子类中是可以直接访问父类的protected变量
class Some
{
protected int x;
Some() {} //子类没有指定构造函数,故必须有无参构造函数
Some(int x)
{
this.x = x;
}
}
class Other extends Some
{
Other(int x1)
{
x = x1; //子类直接访问父类的protected变量
}
}
public class Test
{
public static void main(String[] args)
{
new Other(10);
}
}
在子类中可以通过子类的对象访问父类中的protected变量
import java.util.*;
class Some
{
protected int x;
Some() {}
Some(int x)
{
this.x = x;
}
}
class Other extends Some
{
Other() {}
Other(int x1)
{
Other o = new Other(); //子类可以通过子类的对象访问父类中的protected变量
o.x = x1;
}
}
public class Test
{
public static void main(String[] args)
{
new Other(10);
}
}