- 测试文件目录结构
- private
- protected
- public
- default
- 总结
环境:JDK11
- 同一类中
package a;
public class Student {
private int a = 3;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
}
- 子类
package a;
public class Student_son extends Student{
public int getStudent_a(){
return a;
}
}
- 同一包不同类
package a;
public class Main {
public static void main(String[] args) {
Student student = new Student();
int student_a = student.a;
}
}
- 其他包
package b;
import a.Student;
public class Person {
public static void getStudent_a(){
Student student = new Student();
System.out.println(student.a);
}
}
protected小结:private只能在类中访问
- 同一类中
package a;
public class Student {
protected int a = 3;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
}
同一类中可以访问
- 同一包下子类
package a;
public class Student_son extends Student{
public int getStudent_a(){
return a;
}
}
子类中可以访问
- 不同包下子类
package b;
import a.Student;
public class Student_son2 extends Student {
public int getStudent_a(){
return a;
}
}
不同包下子类可以访问
- 同一包不同类
package a;
public class Main {
public static void main(String[] args) {
Student student = new Student();
int student_a = student.a;
}
}
同一包不同类可以访问
- 其他包
package b;
import a.Student;
public class Person {
public static void getStudent_a(){
Student student = new Student();
System.out.println(student.a);
}
}
不同包下不可访问
public小结:protected可在同一包下访问,或子类(可在不同包中)中访问
- 同一类中
package a;
public class Student {
public int a = 3;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
}
- 子类
package a;
public class Student_son extends Student{
public int getStudent_a(){
return a;
}
}
- 同一包不同类
package a;
public class Main {
public static void main(String[] args) {
Student student = new Student();
int student_a = student.a;
}
}
- 其他包
package b;
import a.Student;
public class Person {
public static void getStudent_a(){
Student student = new Student();
System.out.println(student.a);
}
}
default小结:public可在任何地方中访问
- 同一类中
package a;
public class Student {
int a = 3;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
}
- 同一包下子类
package a;
public class Student_son extends Student{
public int getStudent_a(){
return a;
}
}
- 不同包下子类
package b;
import a.Student;
public class Student_son2 extends Student {
public int getStudent_a(){
return a;
}
}
不同包下子类不能访问
- 同一包不同类
package a;
public class Main {
public static void main(String[] args) {
Student student = new Student();
int student_a = student.a;
}
}
- 其他包
package b;
import a.Student;
public class Student_son2 extends Student {
public int getStudent_a(){
return a;
}
}
其他包不可访问
总结小结:default只能在同一包下访问
| 类型 | 同一类中 | 同一包下子类 | 不同包下子类 | 同一包不同类 | 其他包 |
|---|---|---|---|---|---|
| private | √ | × | × | × | × |
| protected | √ | √ | √ | √ | × |
| public | √ | √ | √ | √ | √ |
| default | √ | √ | × | √ | × |
作用域范围:public>protected>default>private
Notes:protected 同一包或者子类(可以不同包)可以访问,default只能同一包下(可以不为子类)访问



