9.接口-java笔记

1.抽象类
抽象是普通类和接口之间的中庸之道。
接口所有的方法都没有方法体。抽象类有些方法是抽象的,无方法体,有些是有方法体的。
但是抽象类和接口都不能实例化,都是继承用的。
如果一个抽象类被继承,其抽象应当被实现,否则导出类也是抽象类。
抽象类里可以没有抽象方法,abstract可以是该类无法实例化。
2.接口
可以有域,但默认都是static,final
方法都没方法体,且自动都是public,所以实现一个接口,接口中定义的方法都必须定义为public。
interface Instrument {
  // Compile-time constant:
  int VALUE = 5; // static & final
  // Cannot have method definitions:
  void play(Note n); // Automatically public
  void adjust();
}
使用接口的核心原因:可以依次向转型为每一个接口。其次是防止被实例化。
选抽象类还是选接口?如果创建不带任何方法和域的基类时,选接口。如果某事物要成为基类第一选择是接口。
3.接口中方法名
如果接口和其他基类中有相同的方法,那么只要能找到该方法定义就合法。
尽量避免这种情况。
4.扩展接口
interface Monster{ void menace();}
interface DangerousMonster extends Monster(){void destroy();}
5.接口中的域
由于域是static final所以只有一份,且在用之前一定得被初始化。
6.为什么要用接口构建诸如工厂之类的模式? 原因是想要创建框架,框架是通用的。下面有代码可以参考。
nterface Service {
  void method1();
  void method2();
}

interface ServiceFactory {
  Service getService();
}

class Implementation1 implements Service {
  Implementation1() {} // Package access
  public void method1() {print("Implementation1 method1");}
  public void method2() {print("Implementation1 method2");}
}   

class Implementation1Factory implements ServiceFactory {
  public Service getService() {
    return new Implementation1();
  }
}

class Implementation2 implements Service {
  Implementation2() {} // Package access
  public void method1() {print("Implementation2 method1");}
  public void method2() {print("Implementation2 method2");}
}

class Implementation2Factory implements ServiceFactory {
  public Service getService() {
    return new Implementation2();
  }
}   

public class Factories {
  public static void serviceConsumer(ServiceFactory fact) {
    Service s = fact.getService();
    s.method1();
    s.method2();
  }
  public static void main(String[] args) {
    serviceConsumer(new Implementation1Factory());
    // Implementations are completely interchangeable:
    serviceConsumer(new Implementation2Factory());
  }
} /* Output:
Implementation1 method1
Implementation1 method2
Implementation2 method1
Implementation2 method2
*///:~




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值