Thinking in Java 笔记碎片

2017-08-26  本文已影响17人  LilacZiyun

复用类

P135 垃圾收集器可能永远也无法被调用,即使被调用,它也可能以任何他想要的顺序来回收对象。因此最好除了内存回收以外,不要依赖垃圾回收器做任何事情。如果需要清理(如关闭文件等),最好自己编写清理方法,且不要使用finalize()方法。

多态

注意:

class Cycle extends Shape {
    void f() {
        OutUtil.print("I am the child class -- Cycle!");
    }
}
public class Shape {
    private void f() {
        OutUtil.print("I am the base class -- Shape!");
    }
    public static void main(String[] args) {
        Shape s = new Cycle();
        s.f();
    }
}
// Output:
I am the base class -- Shape!
class Super{
    String ss = "String in Super";
    static void staticf(){
        OutUtil.print("staticf() in Super");
    }
    void commonf(){
        OutUtil.print("commonf() in Super");
    }
}
class Sub extends Super{
    String ss = "String in Sub";
    static void staticf(){
        OutUtil.print("f() in Sub");
    }
    void commonf(){
        OutUtil.print("commonf() in Sub");
    }
}
public class MultiType {
    //  Thinking in Java P156 域和静态方法的多态性
    public static void main(String[] args) {
        Super sup = new Sub();
        OutUtil.print(sup.ss);
        sup.staticf();
        sup.commonf();
    }
}
//Output:
String in Super
staticf() in Super
commonf() in Sub
public class ReferenceCounting {
    public static void main(String[] args) {
        Compose[] composes = new Compose[5];
        Share s = new Share();
        for (int i = 0; i < 5; ++i){
            composes[i] = new Compose(s);
        }
        for (int i = 0; i < 5; ++i){
            composes[i].dispose();
        }
    }
}
class Share {
    private int refCount = 0;       // 引用计数器
    private static long counter = 0; // 利用counter和id记录当前创建的Share实例数
    private final long id = counter++;
    public Share() {
        OutUtil.print(this.toString());
    }
    public void addRef() {
        refCount++;
    }
    public void dispose() {
        // 方法内部需要将引用计数减1
        if (--refCount == 0) {
            OutUtil.print("dispose " + this);
        }
    }
    @Override
    public String toString() {
        return "Share " + id;
    }
}
class Compose {
    private Share share;
    private static long counter = 0;
    private final long   id = counter++;
    public Compose(Share share) {
        this.share = share;
        share.addRef();     // 创建一个新对象时,需要将共享变量的引用计数加1
        OutUtil.print(this.toString());
    }
    public void dispose(){
        OutUtil.print("dispose " + this);
        share.dispose();
    }
    @Override
    public String toString() {
        return "Compose " + id;
    }
}
//Output:
Share 0
Compose 0
Compose 1
Compose 2
Compose 3
Compose 4
dispose Compose 0
dispose Compose 1
dispose Compose 2
dispose Compose 3
dispose Compose 4
dispose Share 0

Java运行时多态性:

上一篇 下一篇

猜你喜欢

热点阅读