java权限修饰符

时间:2021-03-29 21:08:19
权限修饰符 本类 同一个包下(子类或者无关类) 不同包下(子类) 不同包下(无关类)
private Y N N N
默认(default) Y Y N N
protected Y Y Y N
public Y Y Y Y

父类Father:

package org.danni.Demo1;

public class Father {
private void show(){
System.out.println("private:show");
}

void show1(){
System.out.println("default:show");
}

protected void show2(){
System.out.println("protected:show");
}

public void show3(){
System.out.println("public:show");
}

public static void main(String[] args) {
Father f = new Father();
f.show(); //private:show
f.show1(); //default:show
f.show2(); //protected:show
f.show3(); //public:show
}
}

同一个包下的子类Son:

package org.danni.Demo1;


public class Son extends Father{
public static void main(String[] args) {
//同一个包下的子类
Son s = new Son();
//f.show();
s.show1(); //default:show
s.show2(); //protected:show
s.show3(); //public:show
}
}

同一个包下的普通类Test:

package org.danni.Demo1;

public class Test {
public static void main(String[] args) {
//同一个包下普通类
Father f = new Father();
//f.show();
f.show1(); //default:show
f.show2(); //protected:show
f.show3(); //public:show
}
}

不同包下的子类Son2:

package org.danni.Demo2;

import org.danni.Demo1.Father;

public class Son2 extends Father{
public static void main(String[] args) {
//不同包下的子类
Son2 s = new Son2();
//s.show();
//s.show1();
s.show2(); //protected:show
s.show3(); //public:show
}
}

不同包下的普通类Test2:

package org.danni.Demo2;

import org.danni.Demo1.Father;

public class Test2 {
public static void main(String[] args) {
//不同包下的普通类
Father f = new Father();
//f.show();
//f.show1();
//f.show2();
f.show3(); //public:show
}
}