您的位置:首页 > 职场人生

黑马程序员——基础知识--继承

2015-10-20 17:57 176 查看
-----------android培训、java培训、java学习型技术博客、期待与您交流!------------

继承(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类:

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()方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: