总结之前的内容,对象(object)指代某一事物,类(class)指代对象的类型。对象可以有状态和动作,即数据成员和方法。
到现在为止,数据成员和方法都是同时开放给内部和外部的。在对象内部,我们利用 this
来调用对象的数据成员和方法。在对象外部,比如当我们在另一个类中调用对象的时,可以使用 对象.数据成员
和 对象.方法()
来调用对象的数据成员和方法。
我们将要 封装(encapsulation)对象的成员(成员包括数据成员和方法),从而只允许从外部调用指定部分的成员。利用封装,我们可以提高对象的易用性和安全性。
对象成员的封装
Java 通过三个关键字来控制对象的成员的 外部可见性(visibility): public
,private
,protected
。
- public:该成员外部可见,即该成员为接口的一部分
- private:该成员外部不可见,只能用于内部使用,无法从外部访问。
- (protected涉及继承的概念,放在以后说)
我们先来封装以前定义的 Human 类:
class Human
{
Human(int h)
{
this.height = h;
System.out.println("I'm born");
}
public int getHeight() // 公共方法
{
return this.height;
}
public void growHeight(int h) // 公共方法
{
this.height = this.height + h;
}
private void breath() // 私有方法
{
System.out.println("hu...hu...");
}
public void repeatBreath(int rep) // 公共方法
{
int i;
for(i = 0; i < rep; i++) {
this.breath();
}
}
private int height; // 私有变量
}
public class Test
{
public static void main(String[] args)
{
Human aPerson = new Human(160);
System.out.println(aPerson.getHeight());
aPerson.growHeight(10);
System.out.println(aPerson.getHeight());
aPerson.repeatBreath(5);
}
}
输出结果:
I'm born
160
170
hu...hu...
hu...hu...
hu...hu...
hu...hu...
hu...hu...
内部方法并不受封装的影响。Human
的内部方法可以调用任意成员,即使是设置为 private
的 height
和 breath()
都可被调用。
外部方法只能调用 public
成员。当我们在 Human
外部时,比如 Test
的 main()
函数中,我们只能调用 Human
中规定为 public
的成员,而不能调用规定为private的成员。
如果我们强行调用 aPerson.breath();
或 aPerson.height
,编译时候都会报错。
通过封装,Human类就只保留了下面几个方法作为接口:
getHeight()
growHeight()
repBreath()
网友评论