码迷,mamicode.com
首页 > 编程语言 > 详细

Java - 继承

时间:2015-08-07 08:18:27      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:mystra   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
 */

技术分享

版权声明:本文为博主原创文章,未经博主允许不得转载。

Java - 继承

标签:mystra   java   继承   

原文地址:http://blog.csdn.net/caroline_wendy/article/details/47333351

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!