- 接口和内部类为我们提供了一种将接口与实现分离的更加结构化的方法。
1、抽象类和抽象方法
- 包含抽象方法的类叫做抽象类。如果一个类包含一个或多个抽象方法,该类必须被限定为抽象的。
- 如果导出类不实现抽象方法,则也是抽象的。
2、接口
- interface关键字产生一个完全抽象的类。
- 当要实现一个接口时,在接口中被定义的方法必须被定义为是public的,不过interface中不声明public默认就是public的。
3、完全解耦
- 只要一个方法操作的是类而非接口,那么就只能使用这个类及其子类。
4、Java中的多重继承
- 接口没有具体的实现,也就是说没有任何与接口相关的存储,因此也就无法阻止多个接口的组合。
- 使用接口的核心原因:为了向上转型为多个基类型。防止客户端程序员创建该类对象,确保这仅仅是建立一个接口。
- 多重继承中方法名称相同、返回值相同不会有问题,但是如果签名或返回类型不同就会有问题。
interface I1 { void f(); }
interface I2 { int f(int i); }
interface I3 { int f(); }
class C { public int f() { return 1; } }
class C2 implements I1, I2 {
public void f() {}
public int f(int i) { return 1; } // overloaded
}
class C3 extends C implements I2 {
public int f(int i) { return 1; } // overloaded
}
class C4 extends C implements I3 {
// Identical, no problem:
public int f() { return 1; }
}
// Methods differ only by return type:
//! class C5 extends C implements I1 {}
//! interface I4 extends I1, I3 {} ///:~
5、适配接口
6、接口中的域
- 放入接口中的任何域都自动是static和final的,所以接口就成为了一种很便捷的用来创建常量组的工具。
- 但是现在有enum了,所以用接口来做常量组工具就没什么意义了。
7、接口与工厂
- 生成遵循某个接口的对象的典型方式就是工厂方法设计方式。
- 在工厂对象上调用的是创建方法,而该工厂对象将生成接口的某个实现的对象。
- 通过这种方式可以将代码与接口实现分离,使得我们可以透明地将某个实现替换为另一个实现。
interface 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
*///:~
网友评论