Java访问权限

Java访问权限

Java中的访问权限有public,private,protected默认的包访问权限,如果类中的属性方法没有显示的指明访问权限,则具有包访问权限,我喜欢称它为packeged权限,很多人也称它为friendly访问权限,而packaged和friendly这两个关键字在实际中都是不存在的。

访问权限的等级最大到最小依次是:public>protected>包访问权限(无关键字)>private

package com.wuxuzhao;

public class MyTest {
	public int mIntPublic=22;
	protected int mIntProtected=33;
	private int mIntPrivate=44;
	int mInt=55;
	
	void printforall()
	{
		// all embelished variable can be accessd by member function
		System.out.println(mIntPublic);
		System.out.println(mIntProtected);
		System.out.println(mInt);
		System.out.println(mIntPrivate);
		
	}
}

package com.wuxuzhao;

//同一个包下的子类
class MyTestDerived extends MyTest
{
	//private int mIntPrivate=64;
	void printforall()
	{
		// the private variable from the base class is not accesed in the derived class
		System.out.println(mIntPublic);
		System.out.println(mIntProtected);
		System.out.println(mInt);
		//System.out.println(mIntPrivate);
		
	}
	
}
//同一个包下的非子类
public class testforaccesspermision
{
	public static void main(String[] args) {
		MyTest objMyTest=new MyTest();
		// in the other class of the same package,the private variable is not accessed
		System.out.println("Access Permission Test");
		System.out.println(objMyTest.mIntPublic);
		System.out.println(objMyTest.mIntProtected);
		System.out.println(objMyTest.mInt);
		//System.out.println(objMyTest.mIntPrivate);  //error;no access
		System.out.println("Access Permission Test:2");
		objMyTest.printforall();
		System.out.println("Access Permission Test in the Derived class:2");
		MyTestDerived objDerived=new MyTestDerived();
		objDerived.printforall();
		
	}
	
}

package com.seie;
import com.wuxuzhao.*;
//其他包的子类
class MyTestInOther extends MyTest
{
	void printforall()
	{
		// the package variable is not accesed in the ohter package
		System.out.println(mIntPublic);
		System.out.println(mIntProtected);
		//System.out.println(mInt);
		//System.out.println(mIntPrivate);
		
	}
}
// 其他包非子类
public class testforaccesspermisioninotherpackage {
	public static void main(String[] args) {
		MyTest objTestInOther=new MyTest();
		//only the public varialbe can be accessed 
		System.out.println("Access Permission Test In Other Package");
		System.out.println(objTestInOther.mIntPublic);
//		System.out.println(objTestInOther.mIntProtected);
//		System.out.println(objTestInOther.mInt);
//		System.out.println(objTestInOther.mIntPrivate);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值