java protected限定符限定只能被子类和同包的类访问
package Keywords;
public class Father {
protected String IDnum = "12345678";
//只能被子类访问和同包的类访问,在子类当中可以是保护和公有
//意思是Father 的id,可以被son、mother 知道,也可以通过son,被其他人知道。除此之外,不能被知道
}
package Keywords;
public class Mather {
protected String IDnum2 ="12346789";//可以被子类或同包类访问
public static void main(String[] args) {
Father father =new Father();
System.out.println(father.IDnum); //12345678 ,同一个包的其他类可以直接访问
Mather mather = new Mather();
System.out.println(mather.IDnum2); //12346789
}
}
package Keywords;
public class Son extends Father{
//修改Father 的IDnum,相当于覆盖
protected String IDnum = "12344567"; //还是限制为protected
}
package Keywords;
public class Grandson extends Son{
public static void main(String[] args) {
Grandson grandson = new Grandson();
System.out.println(grandson.IDnum);//输出Son修改过的IDnum
}
}
以上程序段相当于,父亲和母亲同属一个package,可以互相知道对方的id
son是Father 的子类 ,father 的id可以让son知道(father 的protected),也可通过son,让grandson(son的protected )和其他人(son 的public)知道。
当设置一个private变量时,可以通过一个存取器来访问私有变量
package Keywords;
public class Father {
protected String IDnum = "12345678";
private String birth="1972-6-19";
void setBirth(String str){
this.birth = str; //给私有变量赋值
}
String getBirth(){
return this.birth; //获取私有变量的值,但是都不能通过点·直接访问
}
}
package Keywords;
import java.util.Scanner;
public class Mather {
protected String IDnum2 ="12346789";//可以被子类或同包类访问
public static void main(String[] args) {
Father father =new Father();
System.out.println(father.IDnum);
System.out.println("请输入父亲的生日");
Scanner scanner =new Scanner(System.in);
String birthday = scanner.nextLine();
father.setBirth(birthday);
System.out.println(father.getBirth());
//不能直接用father.birth来读写这个值,必须用到set、get函数,这就限制了访问这个值的特定接口,达到保护的目的。
}
}