重读java编程思想之访问权限控制二

private:私有权限

即除了包含该成员的类之外,其他任何类都无法访问这个成员;

class Sun{

private Sun(){}

static Sun doSun(){

return new Sun();

}

}


public class IceCream{

public static void main(String[] args){

// Sun s = new Sun(); 这是错误的

Sun s = Sun.doSun();

}

}

//上面的例子简单的描述了private的一个作用,控制创建对象,阻止其他的类访问其构造器,不能通过构造器来创建Sun对象,而只能调用静态方法,访问Sun对象内部的方法以达到创建对象的目的,

但是private私有变量后可以通过别名机制获取相关的属性;

java别名机制:

public class Thanl {

int b = 10;

private int a = 1;

int c = a;


/**
* <b>方法说明:</b>
* <ul>
* 获取  a的值
* </ul>
* @return the a
*/
public int getA() {
return a;
}

}

public class Test {


/**
* <b>方法说明:</b>
* <ul>
 * 测试java别名机制
* </ul>
* @param args 
*/
public static void main(String[] args) {
Thanl  t = new Thanl();
Thanl t1 = new Thanl();
Thanl t2 = new Thanl();
System.out.println("t.b:"+t.b+",t1.b:" + t1.b + ",t2.b:" + t2.b);
t1.b = 12;
t2.b = 13;
System.out.println("t.b:"+t.b+",t1.b:" + t1.b + ",t2.b:" + t2.b);
t1 = t2;
System.out.println("t.b:"+t.b+",t1.b:" + t1.b + ",t2.b:" + t2.b);
t1.b = 145;
System.out.println("t.b:"+t.b+",t1.b:" + t1.b + ",t2.b:" + t2.b);

// 通过别名操作获取值

System.out.println("c:"+t.c+", a:"+t.getA());

}
t.b:10,t1.b:10,t2.b:10
t.b:10,t1.b:12,t2.b:13
t.b:10,t1.b:13,t2.b:13
t.b:10,t1.b:145,t2.b:145
c:1, a:1
c:60, a:1


}

==============================================================================================

protected:继承访问权限

protected权限可以依靠继承来理解,或许更容易;

若果一个基类属于一个包,而其一个继承类来自于另外的包,那么唯一可以访问的成员就是源宝的public成员(当然若在基类和子类在一个包下面,可以操作所有包访问权限成员);

有时候基类的创建者希望某些成员的访问权限赋予派生类,而不是所有类,那么protected就派上了用场

protected提供包访问权限,也就是相同包内的其他类可以访问protected元素;

下面的例子以先前的 Cookie作为基类,来访问其中的bite()方法;

import test.dessert.Cookie;

public class Son extends Cookie{

public Son (){

System.out.println("Son  constructor");

}

public void chomp(){

// bite();      // 不能访问bite()方法,编译报错

}

public static void main(String [] args){

Son s = new Son()

s.chomp();

}

}

// output:

Cookie constructor

Son constructor

但是若果我们把Cookie改成这样

public class Cookie(){

public Cookie(){

System.out.println("Cookie constructor");

}

protected void bite(){

System.out.println("bite");

}

}

现在bite()对于所有继承字Cookie的类而言,也是可以使用的。

public class Son1 extends Cookie{

public Son1(){

system.out.println(“Son1 constructor”);

}

public void chomp(){

bite(); //protected method

}

public static void main(String [] args){

Son1 s = new Son1();

s.chomp();

}

}

/*

OutPut:

Cookie constructor

Son1 constructor

*/

//在此需要注意的是bite()也具有包访问权限,但是不是public的


 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值