【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继承

相关文章
相关标签/搜索