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
*/
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/caroline_wendy/article/details/47333351