继承(inheritance)是面向对象的重要概念。继承是除组合(composition)之外,提高代码重复可用性(reusibility)的另一种重要方式。我们在组合(composition)中看到,组合是重复调用对象的功能接口。我们将看到,继承可以重复利用已有的类的定义。
类的继承
我们之前定义类的时候,都是从头开始,详细的定义该类的每一个成员。比如下面的Human类:
如果方法名和参数列表都相同呢? 在衍生层时,我们还可以通过super和this来确定是哪一个方法。而在外部时,我们呈现的只是统一接口,所以无法同时提供两个方法。这种情况下,Java会呈现衍生层的方法,而不是基层的方法。
这种机制叫做方法覆盖(method overriding)。方法覆盖可以被很好的利用,用于修改基类成员的方法。比如,在衍生层,也就是定义Woman时,可以修改基类提供的breath()方法:
比如下面的程序中,Human类有一个构造方法:
/**
* constructor
*/
public Human(int h)
{
this.height = h;
}
/**
* 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类的定义及其构造方法:
/**
* new method
*/
public Human giveBirth()
{
System.out.println("Give birth");
return (new Human(20));
}
/**
* override Human.breath()
*/
public void breath()
{
super.breath();
System.out.println("su...");
}
}
总结
extends
method overriding
protected
super.member, super()