【Java 基礎篇】【第九課】繼承

繼承就是爲了提升代碼的複用率。java

利用繼承,咱們能夠避免代碼的重複。讓Woman類繼承自Human類,Woman類就自動擁有了Human類中全部public成員的功能。
咱們用extends關鍵字表示繼承:編程

看代碼吧:ide

class Human
{
    /*由於類中顯式的聲明瞭一個帶參數構造器,因此默認的構造器就不存在了,可是你在子類的構造器中並無顯式
     * 的調用父類的構造器(建立子類對象的時候,必定會去調用父類的構造器,這個不用問爲何),沒有顯式調用
     * 的話,虛擬機就會默認調用父類的默認構造器,可是此時你的父類的默認構造器已經不存在了,這也就是爲何父
     * 類中必須保留默認構造器的緣由。
     * PS.應該養成良好的編程習慣,任何咱們本身定義的類,都顯式的加上默認的構造器,之後更深刻的學習以後,
     * 會發現有不少好處
     */
    public Human()
    {
    }
    public Human(int h)
    {
        System.out.println("human construction");
        this.height = h;
    }
    
    public int getHeight()
    {
        return this.height;
    }
    
    public void growHeight(int h)
    {
        this.height = this.height + h;
    }
    
    public void breath()
    {
        System.out.println("hu.....hu.....");
    }
    
    private int height;
}


class Woman extends Human
{
    public Human giveBirth()
    {
        System.out.println("Give birth");
        return (new Human(20));
    }
}


public class test 
{
    public static void main(String[] args)
    {
        Woman girl = new Woman();
        girl.breath();
        girl.growHeight(100);
        System.out.println(girl.getHeight());
        
        Human baby = girl.giveBirth();
        System.out.println(baby.getHeight());
        baby.growHeight(12);
        System.out.println(baby.getHeight());
    }

}

輸出:函數

hu.....hu.....
100
Give birth
human construction
20
32學習

 

須要注意 的地方:this

1.子類中要是要調用基類的成員變量的話,成員變量必須是 protected 或者是 public;spa

2.子類中可使用super關鍵字來指代基類對象,使用super() 至關於調用基類的構造函數,super.成員也能夠訪問。orm

看代碼吧:對象

class Human
{
    
    public Human(int h)
    {
        System.out.println("human construction");
        this.height = h;
    }
    
    public int getHeight()
    {
        return this.height;
    }
    
    public void growHeight(int h)
    {
        this.height = this.height + h;
    }
    
    public void breath()
    {
        System.out.println("hu.....hu.....");
    }
    
    protected int height;
}


class Woman extends Human
{
    public Woman(int h)
    {
        super(h);
        System.out.println("Woman construction");
    }
    
    public Human giveBirth()
    {
        System.out.println("Give birth");
        return (new Human(20));
    }
}


public class test 
{
    public static void main(String[] args)
    {
        Woman girl = new Woman(20);
        girl.breath();
        girl.growHeight(100);
        System.out.println(girl.getHeight());
        
        Human baby = girl.giveBirth();
        System.out.println(baby.getHeight());
        baby.growHeight(12);
        System.out.println(baby.getHeight());
    }

}

輸出結果:
human construction
Woman construction
hu.....hu.....
120
Give birth
human construction
20
32繼承

相關文章
相關標籤/搜索