访问控制对子类定义的影响–从父类proctected成员变量的外包子类访问权限入手
FighterPlane.java
public class FighterPlane {
protected String name;
protected int missileNum;
public void fire(){
if(missileNum>0){
System.out.println("now fire a missile!");
missileNum-=1;
}
else {
System.out.println("no missile left!");
}
}
}
RunPlane.java
public class RunPlane extends FighterPlane {
private void init(){
name = "su35";
missileNum = 5;
}
public static void main(String args[]){
RunPlane fp = new RunPlane();
fp.init();
System.out.println(fp.name);
System.out.println(fp.missileNum);
fp.name="su426";
fp.missileNum = 6;
System.out.println(fp.name);
System.out.println(fp.missileNum);
fp.fire();
}
}
输出结果:
su35
5
su426
6
now fire a missile!
这是声明了一个子类对象的情况下
RunPlane类继承了FighterPlane类,但由于Name和missileNum都是非静态的,不能被静态的main访问,所以必须通过实例化对象再调用,要么fp.init(),要么fp.name=..、fp.missileNum=..。
若声明的是父类对象FighterPlane fp = new FighterPlane();
FighterPlane是RunPlane的父类,且它们不在同一个包里面,FighterPlane中的属性都为proctected,在子类init方法中,可以对他们进行访问,但在子类main静态方法中,不能通过对象引用直接访问。
package1
package li_5_5;
import li_5_5_1.FighterPlane;
public class RunPlane extends FighterPlane {
private void init(){
name = "su35";
missileNum = 5;
System.out.println(name + " " + missileNum);
}
public static void main(String args[]){
RunPlane rPlane = new RunPlane();
rPlane.init();
FighterPlane fp = new FighterPlane();
// fp.init();//can't work!
// fp.name="su444";//can't work!
// fp.missileNum=6;//can't work!
System.out.println(fp.getName());
System.out.println(fp.getmissileNum());
fp.setName("su426");;
fp.setmissileNum(6);
System.out.println(fp.getName());
System.out.println(fp.getmissileNum());
fp.fire();
}
}
package2
package li_5_5_1;
public class FighterPlane {
protected String name;
protected int missileNum;
public String getName(){
return name;
}
public void setName(String _name){
name=_name;
}
public int getmissileNum(){
return missileNum;
}
public void setmissileNum(int _missileNum){
missileNum=_missileNum;
}
public void fire(){
if(missileNum>0){
System.out.println("now fire a missile!");
missileNum-=1;
}
else {
System.out.println("no missile left!");
}
}
}
输出:
su35 5
null
0
su426
6
now fire a missile!
visitor tracker