多态小实例:
先创建一个USB接口:
package interface__study;
/**
* 定义一个USB接口
*/
public interface USB {
void connect();
void unconect();
}
然后创建两个鼠标和键盘对像实现USB接口:
对象在实现USB接口之前都得先重写usb接口的方法,然后在定义自己的独有方法,
package interface__study;
public class mouse implements USB {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public mouse(String name) {
this.name = name;
}
public void click(){
System.out.println("鼠标点击了一件三联");
}
@Override
public void connect() {
System.out.println(name+"鼠标已成功连接");
}
@Override
public void unconect() {
System.out.println(name+"鼠标已成功拔出");
}
}
键盘对象:
package interface__study;
public class Keyboard implements USB{
private String name;
public Keyboard(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void Keydown()
{
System.out.println("小帅哥在键盘上疯狂敲击");
}
@Override
public void connect() {
System.out.println(name+"键盘已成功连接");
}
@Override
public void unconect() {
System.out.println(name+"键盘已成功拔出");
}
}
创建一个Computer类,并且在其中定义USBinstall方法
在usbinstall方法中的形参使用的是接口usb,方法中使用instanceof方法判断导入的实参是键盘还是鼠标,继而强制转换USB类并且使用鼠标或键盘类的独有的方法(接口调用只能调用接口所有的方法而不能调用实现类的独有方法)
package interface__study;
public class Computer {
public String name;
public Computer() {
}
public Computer(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void start(){
System.out.println(name+"已成功运行!");
}
public void USBinstall(USB u)
{
u.connect();
if (u instanceof Keyboard)
{
Keyboard keyboard=(Keyboard) u;
keyboard.Keydown();
}else if (u instanceof mouse)
{
mouse m=(mouse) u;
m.click();
}
u.unconect();
}
}
创建Test类进行测试
package interface__study;
public class test {
public static void main(String[] args) {
Computer a=new Computer();
a.setName("外星人");
a.start();
Keyboard K=new Keyboard("惠普");
mouse m=new mouse("小老鼠");
a.USBinstall(m);
a.USBinstall(K);
}
}