接口实例

文章目录

  • 运动员实现:
  • usb接口实现

运动员实现:

  • yundongyuan接口:
public interface yundongyuan {
	public void run();
}
  • horse类
public class horse implements yundongyuan {

	@Override
	public void run() {
		System.out.println("马在跑");
	}

}
  • pig类
public class pig implements yundongyuan {

	@Override
	public void run() {
		System.out.println("猪在跑");
	}
}

  • person类
public class person implements yundongyuan{
	@Override
	public void run() {
		System.out.println("人在跑");
	}
}
  • test类
import java.util.ArrayList;

public class test {
	public static void main(String[] args) {
		ArrayList<yundongyuan> list = new ArrayList<>();
		list.add(new pig());
		list.add(new horse());
		list.add(new person());
		
		for(yundongyuan y:list) {
			y.run();
		}
	}
}

usb接口实现

  • usb接口类
public interface usb {

	public void sendMsg(String msg);
}
  • computer类(发送)
public class computer {

	usb u;
	public void input(String msg) {
		System.out.println("计算机录入:"+msg);
		u.sendMsg(msg);
	}
}
  • telephone类(接收)
public class telephone {
	int count=100;
	usb u = new usb() {
		@Override
		public void sendMsg(String msg) {	
			telephone.this.count=200;
			System.out.println("手机收到:"+msg);
		}
	};
}
  • test类
public class test {
	public static void main(String[] args) {
		computer c = new computer();	//发送方:定义接口,调用接口方法
		telephone p = new telephone();	//接收方:定义接口,实现接口
		c.u = p.u;						//监听器:将接受方实现的接口给发送方
		c.input("啊,我死了");
	}
}

你可能感兴趣的:(SE)