Java interface variables as parameters

If a method parameter is an interface type, we can assign a reference to an object created by a class that implements a certain interface to an interface variable declared by the interface, then the interface variable can call the interface method implemented by the class (put the object's The reference is assigned to the interface variable, and the latter can call the interface method implemented by the former class)

package 第七章7_4;

interface SpeakHello{
    
    
	void speakHello();
}                                        //创建接口
class Chinese implements SpeakHello{
    
          //定义一使用接口的类
	public void speakHello(){
    
                 //重写接口抽象方法
		System.out.println("中国人习惯问候语你好");
	}
}
class English implements SpeakHello{
    
    
	public void speakHello(){
    
    
		System.out.println("英国人习惯问候语Hello");
	}
}
class KindHello{
    
    
	public void lookHello(SpeakHello hello){
    
        //定义接口类型参数
		hello.speakHello();                      //接口回调
	}
}
public class Example7_4 {
    
    

	/**
	 * @param args
	 */
	public static void main(String[] args) {
    
    
		// TODO 自动生成的方法存根
		KindHello kindHello = new KindHello();
		kindHello.lookHello(new Chinese());    //括号里内容是把Chinese类对象的引用赋给接口类型变量hello;括号外是调用Chinese类重写的接口方法
		kindHello.lookHello(new English());
	}

}
//如果一方法参数是接口类型,我们就可以把实现某一接口的类创建的对象的引用赋给该接口声明的接口变量中,那么该接口变量就可以调用被类实现的接口方法(把对象的引用赋给接口变量,后者就可以调用前者类实现的接口方法)

insert image description here

package 上机实践7_10;

interface DogState{
    
    
	void showState();
}
class SoftlyState implements DogState{
    
    
	public void showState(){
    
    
		System.out.println("在主人面前听主人命令");
	}
}
class MeetEnemyState implements DogState{
    
    
	public void showState(){
    
    
		System.out.println("遇到敌人狂叫,并冲上去咬敌人");
	}
}
class MeetFriendState implements DogState{
    
    
	public void showState(){
    
    
		System.out.println("遇到朋友摇尾巴欢迎");
	}
}
class Dog{
    
    
	DogState state;
	public void cry(){
    
    
		state.showState();
	}
	public void setState(DogState s){
    
    
	state = s;}
}
public class CheckDogState {
    
    

	/**
	 * @param args
	 */
	public static void main(String[] args) {
    
    
		// TODO 自动生成的方法存根
		Dog 小狗 = new Dog();
		小狗.setState(new SoftlyState());
		小狗.cry();
		小狗.setState(new MeetEnemyState());
		小狗.cry();
		小狗.setState(new MeetFriendState());
		小狗.cry();
	}

}

insert image description here

Guess you like

Origin blog.csdn.net/qq_44543774/article/details/130139071