继承的多态是通过重写父类一个方法的几个不同子类来实现的,同样的道理,基于接口的多态可以通过实现接口覆盖接口中对应方法的几个不同的类来实现,一样的,接口类型的引用指向了实现该接口的一个类实例对象,通过对象引用来执行对应的方法
与继承多态类似,来一个例子
interface Interest {
public void love();
public void hate();
}
class Sports implements Interest {
public void love() {
System.out.println("Love playing football");
}
public void hate() {
System.out.println("Hate running");
}
}
class Scripts implements Interest {
public void love() {
System.out.println("Love python");
}
public void hate() {
System.out.println("Hate perl");
}
}
public class Main {
public static void main(String[] args) {
Interest[] interest = new Interest[2];
interest[0] = new Sports();
interest[1] = new Scripts();
for (int i = 0; i < 2; i++) {
interest[i].love();
interest[i].hate();
}
}
}
通过一个接口类型的引用,分别调用实现它的子类所实现的方法,这就是基于接口的多态
