如果一个方法的参数是接口类型,我们就可以将任何实现该接口的类的实例引用传递给该接口的参数,那么接口参数就可以回调类实现的接口方法。
interface SpeakHello{
void speakHello();
}
class Chinese implements SpeakHello{
public void speakHello(){
System.out.println("中国人习惯问候语:你好,吃饭了吗?");
}
}
class English implements SpeakHello{
public void speakHello(){
System.out.println("英国人习惯问候语:你好,天气不错");
}
}
class KindHello{
public void lookHello(SpeakHello hello){ //这里只用传接口类型的值,也就是 引用类型的值,也就是说传递了一个接口的实现类的对象的引用。而这个引用可以直接调用实现接口的类的方法
hello.speakHello();
}
}
public class Example6_5 {
public static void main(String args[]){
KindHello kindHello=new KindHello();
kindHello.lookHello(new Chinese());
kindHello.lookHello(new English());
}
}
TRANSLATE with x
English
TRANSLATE with
COPY THE URL BELOW
Back
EMBED THE SNIPPET BELOW IN YOUR SITE
Enable collaborative features and customize widget: Bing Webmaster Portal
Back
原创文章,作者:3628473679,如若转载,请注明出处:https://blog.ytso.com/271585.html