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