Java - 继承

Java未写继承的类, 默认继承标准基类Object.
每个类都可以包含一个main()静态方法, 用于单元测试.
继承是对类的复用, 函数内使用super调用基类的相同方法, 区分递归.
派生类中可以添加新的方法, 对基类进行扩展.

代码:

/** * 继承 * <p/> * Created by wang on 15/8/7. */

class Cleaner {
    private String s = "Cleaner";

    public static void main(String[] args) {
        Cleaner x = new Cleaner();
        x.dilute().apply().scrub();
        System.out.println(x);
    }

    public void append(String a) {
        s += a;
    }

    public Cleaner dilute() {
        append(" dilute");
        return this;
    }

    public Cleaner apply() {
        append(" apply");
        return this;
    }

    public Cleaner scrub() {
        append(" scrub");
        return this;
    }

    @Override
    public String toString() {
        return s;
    }
}

class Detergent extends Cleaner {
    public static void main(String[] args) {
        Detergent d = new Detergent();
        ((Detergent) d.dilute().apply()).scrub().foam();
        System.out.println(d);
    }

    @Override
    public Detergent scrub() {
        append(" Detergent: scrub()");
        super.scrub();
        return this;
    }

    public Detergent foam() {
        append(" foam");
        return this;
    }
}

public class Disinfectant extends Detergent {
    public static void main(String[] args) {
        Disinfectant d = new Disinfectant();
        ((Disinfectant) d.dilute().apply()).scrub().sterilize();
        System.out.println(d);
        Detergent.main(args);
        Cleaner.main(args);
    }

    @Override
    public Disinfectant scrub() {
        append(" Disinfectant: scrub()");
        super.scrub();
        return this;
    }

    public Disinfectant sterilize() {
        append(" sterilize");
        return this;
    }
}
/** * Output: Cleaner dilute apply Disinfectant: scrub() Detergent: scrub() scrub sterilize Cleaner dilute apply Detergent: scrub() scrub foam Cleaner dilute apply scrub */

在继承中, 带参数的构造器, 必须在导出类中第一个被调用(super), 否则报错.

/** * 带参数的构造器 * <p/> * Created by wang on 15/8/8. */
class Game {
    Game(int i) {
        System.out.println("Game Constructor:" + i);
    }
}

class BoardGame extends Game {
    BoardGame(int i) {
        super(i);
        System.out.println("BoardGame Constructor:" + i);
    }
}

public class Chess extends BoardGame {
    public Chess() {
        super(11);
        System.out.println("Chess Constructor");
// super(11); // 报错
    }

    public static void main(String[] args) {
        new Chess();
    }
}
/** * 报错: 对super的调用必须是构造函数中的第一个语句 */

Java - 继承_第1张图片

你可能感兴趣的:(java,继承,Mystra)