
4.10 访问权限

访问权限使用访问修饰符进行限制,访问修饰符有private、protected 和public,它们都是Java 中的关键字。
1.什么是访问权限
访问权限是指对象是否能够通过运算符 “.” 操作自己的变量或通过运算符 “.” 调用类中的方法。
在编写类时,类中的实例方法总是可以操作该类中的实例变量和类变量;类方法总是可以操作该类中的类变量,与访问修饰符没有关系。
2.私有变量和私有方法
使用private 修饰的成员变量和方法被称为私有变量和私有方法。例如:

如果现在有一个B 类,则在B 类中创建一个A 类的对象后,该对象不能访问自己的私有变量和方法。例如:

如果一个类中的某个成员是私有类变量,则在另一个类中,不能通过类名来操作这个私有类变量。如果一个类中的某个方法是私有类方法,则在另一个类中,也不能通过类名来调用这个私有类方法。
3.公有变量和公有方法
使用public 修饰的变量和方法被称为公有变量和公有方法。例如:

使用public 修饰的变量和方法在任何一个类中创建对象后都会被访问到。例如:

4.友好变量和友好方法
不使用private、public 和protected 修饰的成员变量和方法被称为友好变量和友好方法。例如:

对于同一个包中的两个类而言,如果在一个类中创建了另一个类的对象,则该对象能访问自己的友好变量和友好方法。例如:

学习笔记
如果源文件使用import 语句引入了另一个包中的类,并使用该类创建了一个对象,则该类的这个对象将不能访问自己的友好变量和友好方法。
5.受保护的成员变量和方法
使用protected 修饰的成员变量和方法被称为受保护的成员变量和方法。例如:

对于同一个包中的两个类而言,一个类在另一个类创建对象后可以通过该对象访问自己的protected 变量和protected() 方法。例如:

6.public 类与友好类
在声明类时,如果在关键字class 前面加上关键字public,则这样的类就是公有的类。例如:

可以在任何另外一个类中,使用public 类创建对象。如果一个类不使用public 修饰,例如:

则这个没有被public 修饰的类就称为友好类。在另一个类中使用友好类创建对象时,必须保证它们在同一个包中。