核心思想:用抽象构建框架,用实现扩展细节,
我们举个例子来看,
比如这里有个蛋糕,蛋糕有三个属性,编号,价格,口味
那么我们可以定义一个接口,
interface ICake(){
public void getId();
public void getValue();
public void getTaste();
}
class SnowCake implements ICake{
private Integer id;
private String taste;
private Double price;
public SnowCake(Integer id, String taste, Double price) {
this.id = id;
this.taste = taste;
this.price = price;
}
@Override
public Integer getID() {
return this.id;
}
@Override
public String getTaste() {
return this.taste;
}
@Override
public Double getPrice() {
return this.price;
}
}
这个时候如果我们想获取价格,我们怎么获取呢,我们是通过接口去获取的,
class MyView(){
public void showView(ICake iCake){
System.out.println("my price is"+iCake.getPrice);
}
}
public class Test {
public static void main(String[] args) {
MyView sc = new MyView();
System.out.println(sc.showView(new SnowCake("1","香草味","13")));
}
}
打印出来的是 my price is 13.