接口定义了一个新的引用类型。可以使用接口类型来声明变量,在方法中声明参数类型,作为方法的返回类型等。
interface Shape {
void draw();
}
public class Main {
// interface type as instance variable
private Shape myShape;
// interface type as parameter type for a constructor
public Main(Shape s) {
this.myShape = s;
}
// interface type as return type of a method
public Shape getShape() {
return this.myShape;
}
// interface type as parameter type for a method
public void setShape(Shape s) {
this.myShape = s;
}
public void letItSwim() {
// interface type as a local variable
Shape locaShape = null;
locaShape = this.myShape;
// interface variable can invoke methods
// declared in the interface and the Object class
locaShape.draw();
}
}
接口类型的变量是指其类实现该接口的内存中的对象。使用接口类型的变量或直接使用接口名称来访问接口中声明的任何常量字段。
最好使用接口名访问接口的常量。使用接口类型的变量来调用接口中声明的任何方法。接口类型的变量可以调用java.lang.Object
类的任何方法。
默认情况下,接口类型的实例或静态变量将初始化为null
。