1.概念
访问修饰符就是控制访问权限的修饰符号
2.类的访问修饰符
类的访问修饰符只有两种:public修饰符和默认修饰符(不写修饰符就是默认)
public 修饰符修饰类表示可以公开访问。默认修饰符修饰类表示该类只能在同一个包中可以访问
示例
package cn.lyxq.test04;
//使用默认修饰符修饰类时,该类只能在同一个包的其它类中使用
class Teacher {
}
package cn.lyxq.test04;
public class School {
private Teacher[] teachers;//可以访问Teacher类
}
package cn.lyxq.test04.test;
import cn.lyxq.test04.Teacher;
public class TeacherTest {
public static void main(String[] args) {
Teacher teacher = new Teacher();
}
}
3.类成员访问修饰符
类成员包括了成员属性和成员方法。类成员访问修饰符换言之就是成员属性和成员方法的访问修饰符。
示例
package cn.lyxq.test04;
public class School {
private Teacher[] teachers;//可以访问Teacher类
//使用默认修饰符修饰name属性
String name;
protected int age;
public String address;
public void show(){
System.out.println(teachers.length + "\t" + name + "\t" + age +"\t" + address );
}
}
package cn.lyxq.test04;
public class SchoolTest {
public static void main(String[] args) {
School school = new School();
//外部不能访问private修饰的属性
System.out.println(school.teacher);
System.out.println(school.name);
System.out.println(school.age);
System.out.println(school.address);
}
}
package cn.lyxq.test04.test;
import cn.lyxq.test04.School;
public class SchoolTest1 {
public static void main(String[] args) {
School school = new School();
//外部不能访问private修饰的属性
System.out.println(school.teacher);
System.out.println(school.name);
System.out.println(school.age);
System.out.println(school.address);
}
}