Thinking in java 笔记----权限访问控制

 一、Java访问权限控制

1)在类的内部都可以访问到四种权限

package com.learn.permission;

public class TestPermission {
	private String privateStr = "private";
	protected String protectedStr = "protected";
	public String pulicStr = "public";
	String packageStr = "package";
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TestPermission test = new TestPermission();
		System.out.println(test.pulicStr);
		System.out.println(test.packageStr);
		System.out.println(test.protectedStr);
		System.out.println(test.privateStr);
	}	
}

 

2)同一包内不同类,private不可见

package com.learn.permission;

public class TestInPackage {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TestPermission test = new TestPermission();
		System.out.println(test.pulicStr);
		System.out.println(test.packageStr);
		System.out.println(test.protectedStr);
//		System.out.println(test.privateStr); //private is not visible in different class of same pacakge

	}
}

 

3)同一包里子类,private不可见

package com.learn.permission;

public class TestPermissionExtends extends TestPermission {
	public static void main(String[] args){
		TestPermissionExtends test = new TestPermissionExtends();
		System.out.println(test.pulicStr);
		System.out.println(test.packageStr);
		System.out.println(test.protectedStr);
		//after extend , the private field or method is not available
//		System.out.println(test.privateStr);
	}
}

 

4) 不同包非子类,只有public可见

package com.learn.chapter1;

import com.learn.permission.TestPermission;


public class TestOutPackage {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TestPermission test = new TestPermission();
		System.out.println(test.pulicStr);
		//outside the package , only the public is available
//		System.out.println(test.packageStr);
//		System.out.println(test.protectedStr);
//		System.out.println(test.privateStr);
	}

}

5)不同包里子类,只有public和protected可见

package com.learn.chapter1;

import com.learn.permission.TestPermission;

public class TestPermissionExtend extends TestPermission {
	public static void main(String[] args){
		TestPermissionExtend test = new TestPermissionExtend();
		System.out.println(test.pulicStr);
//		System.out.println(test.packageStr);
		System.out.println(test.protectedStr);
		//after extend , the private field or method is not available
//		System.out.println(test.privateStr);
	}
}


 总结:

Public:对任意类可见

protected :与包访问权限类似,只是被继承的时候可见,这个时候相当于private,不过仍可以继承可见

包访问权限:只对当前包可见

private :只对当前类可见

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值