Java protected限定符,private限定符和private变量的存取器

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函数,这就限制了访问这个值的特定接口,达到保护的目的。
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值