美文网首页
读 4 Techniques for Writing Bette

读 4 Techniques for Writing Bette

作者: shengjk1 | 来源:发表于2020-03-12 22:06 被阅读0次

4 Techniques for Writing Better Java一文中,作者提到了 4个小技巧。

1.协变返回类型,说了就是可以返回子类。java4( java 编程思想第四版) 中已经介绍过了,这里就不再细究。直接上例子:

public interface CustomCloneable {
    public Object customClone();
}

public class Vehicle implements CustomCloneable {
    private final String model;
    
    public Vehicle(String model) {
        this.model = model;
    }
    
    @Override
    //返回子类,避免了强制转换
    public Vehicle customClone() {
        return new Vehicle(this.model);
    }
    
    public String getModel() {
        return this.model;
    }
    
    
    public static void main(String[] args) {
        Vehicle originalVehicle = new Vehicle("Corvette");
        Vehicle clonedVehicle = originalVehicle.customClone();
        System.out.println(clonedVehicle.getModel());
    }
}

对于返回子类型或者叫做协变返回类型来说,遵循着下面一下小规则:

1. 父类是 void 的话,子类也是void
2. 父类为基本类型,子类也必须为相同的基本类型
3. 对于泛型来说,不能返回 泛型参数的子类,但可以返回泛型类的子类

对于第3点来说是什么意思呢?
正确范例:

public interface Animal {
    public List<Animal> getAnimals();
}

class Dog implements Animal {
    @Override
    //对于泛型来说,不能返回 泛型参数的子类,但可以返回泛型类的子类
    public ArrayList<Animal> getAnimals() {
        return null;
    }
}

错误范例

public interface Animal {
    public List<Animal> getAnimals();
}

class Dog implements Animal {
    @Override
    //对于泛型来说,不能返回 泛型参数的子类,但可以返回泛型类的子类
    public ArrayList<Dog> getAnimals() {
        return null;
    }
}

2.相交泛型,特别精彩,对于面向对象设计模式等很好的利用了起来,需要在慢慢提会一下

3.如何通过 try-resource 自动关闭连接?
通过实现 AutoCloseable 接口

4.final 类以及final 方法就不再论述,Java编程思想已经说得很透彻了。

相关文章

网友评论

      本文标题:读 4 Techniques for Writing Bette

      本文链接:https://www.haomeiwen.com/subject/ueegjhtx.html