(1)接口与类类似,但是接口中仅仅包括方法的声明,而不包括方法的实现部分。
例如Shape接口定义
public interface Shape
{
public double getArea();
public double getZhouchang();
}
尽管定义形式与类类似,但是接口不能被实例化。即new Shape()是无法通过编译的。
(2)但是一个接口可以同时被多个类实现,从而这些实现了该接口的类可以体现多态性。
注意:实现接口的类必须实现该接口中的所有方法。例如Rectangle类和Circle类实现了Shape接口
public class Rectangle implements Shape
{
private double width,height;
public Rectangle(double width,double height)
{
this.width=width;
this.height=height;
}
public double getArea()//必须同时实现接口中的所有方法
{
return width*height;
}
public doubel getZhouchang()
{
return 2*(width+height);
}
}
同理,Circle类中可以定义变量radius,同时实现getArea(),getZhouchang()方法。
为体现多态性,例如可利用如下代码:Shape[] shapes=new Shape[2];shapes[0]=new Rectangle(10,20);shapes[1]=new Circle(30);
从而实现多态性
(3)通过接口,可以突破单继承限制。例如一个类虽然只能有一个父类,但是可以实现任意多个接口。
public class <name> extends <superclass name> implements <interface name1>,<interface name2>,<interface name3>,<interface name4>
{
......................................
}