新建一个接口父类:
//只拥有抽象方法的抽象类,可以重写为 interface(接口)
//在interface 中,只有抽象方法,不能有属性或普通方法。
public interface Shape {
//public abstract 可以省略,系统自动添加
double area();
}
建一个对接子类:
//使用 implements 实现接口,必须实现接口中的所有抽象方法
public class Rect implements Shape{
private double w;
private double h;
public double getW() {
return w;
}
public void setW(double w) {
this.w = w;
}
public double getH() {
return h;
}
public void setH(double h) {
this.h = h;
}
public Rect() {
super();
}
public Rect(double w, double h) {
super();
this.w = w;
this.h = h;
}
@Override
public double area() {
return w * h;
}
}
建一个main方法执行
public class Application {
public static void main(String[] args) {
//接口 == 特殊的抽象类
//不能创建 接口 的对象,只能创建实现了接口的子类对象
// Shape shape = new Shape() 不能用
Rect rect = new Rect();
Rect r1 = new Rect(2,2);
Rect r2 = new Rect(6,6);
System.out.println(r1.area());
System.out.println(r2.area());
//使用接口也可以完成多态
//使用一个接口类型 表示所有的子类类型
Computer computer = new Computer();
double totalArea = computer.sumArea(r1, r2);
System.out.println("总面积" + totalArea);
//继承:is - a 关系 XXX是ZZZ的一种
//接口:has - a 关系 XXX有yyy的功能
//按照种类划分,使用继承:猫狗鱼都是动物,继承自Animal
//按照功能划分,使用接口:鸟,超人,飞机,都是会飞的
//一个类只有一个父类,但是可以实现多个接口
}
}