4.4.3 接口的使用

接口机制可以把设计和实现分离,这在java代码里面是怎么体现的呢? 我们用上面的Math做例子:
public static void main(String[]arg){
    Math m=new MathImpl();
    System.out.println(m.abs(-9));
}
注意这条语句:Math m = new MathImpl(); m的类型声明是Math,m的实际类型是MathImpl。调用的函数abs的具体是MathImpl里实现的 其实类似的语法我们已经接触过,那就是List的使用:
List list=new ArrayList();
在这里List就是接口,ArrayList就是具体的类型。 接口的好处主要在以下几点: 1.接口定义了功能,而实现可以有多个,在不同的场合用不同的实现 2.使用实现,不需要修改调用的代码。 对于第2点,我们可以看这样一个伪代码:
public static void main(String[]arg){
    Math m=new MathImpl();
    System.out.println(m.abs(-9));
    接下来,m使用了100多次}
假如要修改m的实现,我们只需要改变m的声明:Math m = new MathImpl(); 例如有另外一个实现MathImpl2: Math m = new MathImpl2(); 我们只需要改这一句,后面所有m的调用,使用的就是MathImpl2的实现。