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);
}
}