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

-----------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()方法。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值