接口实例调用方法,其实接口实现类在调用方法,利用了多态
Interface i = new InterfaceImpl();
i.method();
接口 :Bird.java
package referenceType;
public interface Bird {
void yell();
}
实现类 :BirdImple.java
package referenceType;
public class BirdImpl implements Bird{
@Override
public void yell() {
System.out.println("ji ji ji");
}
}
测试类 :Test.java
package referenceType;
public class Test {
public static void main(String[] args) {
Bird b = new BirdImpl();
b.yell();
}
}
或者增加Chick类,接口类型作为成员变量,构造方法里传入
Chick.java
package referenceType;
public class Chick {
Bird bird;
public Chick(Bird bird) {
this.bird = bird;
}
public void shout(){
bird.yell();
}
}
Test.java
package referenceType;
public class Test {
public static void main(String[] args) {
Bird b = new BirdImpl();
b.yell();
//多一步,将接口实现类传入Chikc构造方法中
Bird b2 = new BirdImpl();
Chick chick = new Chick(b2);
chick.shout();
}
}