java-访问修饰符
同一个类中 同一个包中 不同包中的子类中 不同包中
private OK
(default) OK OK
protected OK OK OK
public OK OK OK OK
package com.demo.test1; import org.junit.Test; /** * 类内 * @author Administrator * */ public class Person { public String uname = "王五"; @Test public void introduceMyself(){ System.out.println(uname); } }
package com.demo.test1; import org.junit.Test; /** * 同一个包 * @author Administrator * */ public class Student { Person p = new Person(); @Test public void test(){ System.out.println(p.uname); } }
package com.demo.test2; import org.junit.Test; import com.demo.test1.Person; /** * 不同包 * @author Administrator * */ public class Parents { public String uname = "haha"; Person p = new Person(); @Test public void test2(){ //把uname用protected修饰,挎包不能访问uname属性 //System.out.println(p.uname); //System.out.println(p.uname); } }
package com.demo.test2; import org.junit.Test; import com.demo.test1.Person; /** * 不同包的子类 * @author Administrator * */ public class Man extends Person{ public int age; Man m = new Man(); Person p = new Person(); @Test public void test3(){ //当前类调用父类属性(protected修饰) System.out.println(m.uname); System.out.println(((Man)p).uname); } }