类的继承
继承(inheritance)是面向对象的重要概念。继承是除组合(composition)之外,提高代码重复可用性(reusibility)的另一种重要方式。我们在组合(composition)中看到,组合是重复调用对象的功能接口。我们将看到,继承可以重复利用已有的类的定义。
类的继承
我们之前定义类的时候,都是从头开始,详细的定义该类的每一个成员。比如下面的Human类:
class Human
{
/**
* accessor
*/
public int getHeight()
{
return this.height;
}
/**
* mutator
*/
public void growHeight(int h)
{
this.height = this.height + h;
}
/** * breath */ public void breath() { System.out.println("hu...hu..."); }
private int height;
}从上面的类定义,我们可以了解该类的所有细节: 该类的数据成员,该类的方法,该类的接口。
现在要定义一个新的类,比如Woman类,并假设Woman与Human类相当类似:
Human & Woman
我们可以像以前一样,从头开始,完整的定义Woman类:
class Woman
{
/**
* accessor
*/
public int getHeight()
{
return this.height;
}
/**
* mutator
*/
public void growHeight(int h)
{
this.height = this.height + h;
}
/** * breath */ public void breath() { System.out.println("hu...hu..."); }
/**
* new method
*/
public Human giveBirth()
{
System.out.println("Give birth");
return (new Human(20));
}
private int height;
}一个程序员在写上面程序的时候,会有很大的烦恼。许多定义都曾在Human类中写过,但我们还要重新敲一遍。Woman类只新增了一个giveBirth()方法 (该方法创建并返回一个新的Human对象)。
利用继承,我们可以避免上面的重复。让Woman类继承自Human类,Woman类就自动拥有了Human类中所有public成员的功能。
我们用extends关键字表示继承:
class Woman extends Human
{ /**
* new method
*/
public Human giveBirth()
{
System.out.println("Give birth");
return (new Human(20));
}
}这样,我们就省去了大量的输入。通过继承,我们创建了一个新类,叫做衍生类(derived class)。被继承的类(Human)称为基类(base class)。衍生类以基类作为自己定义的基础,并补充基类中没有定义的giveBirth()方法。继承关系可以表示为:
继承: 箭头指向基类
可以用以下Test类测试:
public class Test
{
public static void main(String[] args)
{
Woman aWoman = new Woman();
aWoman.growHeight(120);
System.out.println(aWoman.getHeight());
}
}
衍生层
通过继承,我们创建了Woman类。整个过程可以分为三个层次: 基类定义,衍生类定义,外部使用。
基类定义的层次就是正常的定义一个类,比如上面的Human类定义。
在外部使用者看来(比如Test类中创建Woman类对象),衍生类有一个统一的外部接口:
对于外部使用者来说,上述接口就已经足够了。仅从接口看,衍生类也没有什么特别之处。
补充:软件开发 , Java ,