接口内的方法自动会声明为public;成员变量会自动定义为public、static和final(编译时常量)。
一、Java的多重继承
使用接口:
- 为了向上转型为多个基类型
- 防止客户端创建该类的对象,并确保这仅仅是一个接口(与使用抽象类的效果相同)
二、通过继承来扩展接口
三、适配接口
策略模式
四、接口中的域
在接口中定义的域不能是“空final”,但可以被非常量表达式初始化。
五、接口与工厂
//: interfaces/Factories.java
import static net.mindview.util.Print.*;
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
*///:~
接口和抽象类:
抽象类中的抽象方法(其前有abstract修饰)不能用private、static、synchronized、native访问修饰符修饰。原因如下:抽象方法没有方法体,是用来被继承的,所以不能用private修饰。
接口里的变量:只能是公共静态的常量(自动设为public static final)
1. 接口方法,访问权限必须是公共的 public(可省略不写)
2. 接口内只能有公共方法,不能存在成员变量
3. 接口内只能含有未被实现的方法,也叫抽象方法,但是abstract关键字可省略不写。
接口不是类,不能实例化一个接口,但是可以声明接口的变量来引用实现了接口的类对象。
局部内部类不能用public或者private访问修饰符修饰。