接口的使用--当参数传入方法之中。

2020.6.24新加
对于接口,在没有实现方法时可以直接使用内部类的方法调用。

public interface inter{ //接口
void use()
}
pulic  class  computer{   //定义使用接口的类
private interface inter;  
public void useinter(inter){ //使接口当个参数传入方法
print("使用接口")
}
}
main函数{
compter  com=new computer();
com.useinter (new interface(){ //内部类,在这里写接口的实现
void use (){}
print("接口a")
})
}

————————————

当做参数传入方法

public interface Usb{  //usb接口
void open();
void close();
}
public class mouse impliment Usb{  //鼠标实现接口
public void open(){}
public void close(){}
}
public class computer{  //电脑使用接口
  
public void use(Usb usb){       //将接口作为参数传入方法进行使用
usb.open();
usb.close();
}
}
main函数{
computer com =new computer(); 
1:
Usb usb= new mouse(); //将USB实例化,传入use方法中
com.use(usb); //传入参数,使用接口
2:
mouse  mou= new mouse();
com.use(mou);  //传入usb实现类的对象也可以。

}

有多个实现类时用instanceof判断

public void use(Usb usb){
if (usb instanceof  mouse){
mouse mou = (mouse) Usb  //向下转型,由Usb转为mouse ,使用mouse私有方法
}else if (usb instanceof  keybod){//如果传入参数是键盘,就执行键盘的方法。
}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值