初学接口多态
instanceof的用法
举例:usb接口经典例题
public class Test{
public static void main(String[] args) {
Laptop lt = new Laptop();// 创建笔记本实体对象
lt.run();// 笔记本运行
USB u = new Mouse();// 创建鼠标实体对象
lt.useUSB(u);// 笔记本使用鼠标
KeyBoard kb = new KeyBoard();// 创建键盘实体对象
lt.useUSB(kb);// 笔记本使用键盘
lt.shutDown();// 笔记本关闭
}
}
class Laptop {
// 笔记本开启运行功能
public void run() {
System.out.println("笔记本运行");
}
// 笔记本使用usb设备,这时当笔记本对象调用这个功能时,必须给其传递一个符合USB规则的USB设备
public void useUSB(USB usb) {
if(usb!=null) {
usb.open();
//请添加适当代码
if(usb instanceof Mouse){//此处即为instanceof的使用
Mouse m=(Mouse) usb;
m.click();
}
if(usb instanceof KeyBoard){//此处即为instanceof的使用
KeyBoard k= (KeyBoard) usb;
k.type();
}
usb.close();
}
}
public void shutDown() {
System.out.println("笔记本关闭");
}
}
interface USB{
void open();
void close();
}
class Mouse implements USB{
@Override
public void open() {
System.out.println("鼠标开启,红灯闪一闪");
}
@Override
public void close() {
System.out.println("鼠标关闭,红灯熄灭");
}
public void click(){
System.out.println("鼠标单击");
}
}
class KeyBoard implements USB{
@Override
public void open() {
System.out.println("键盘开启,绿灯闪一闪");
}
@Override
public void close() {
System.out.println("键盘关闭,绿灯熄灭");
}
public void type(){
System.out.println("键盘打字");
}
}
代码中的instanceof即是判断传过来的usb是Mouse还是Keyboard,即obj 为 class 接口的实现类
以下内容为搬运过来的以便参考
- obj 为 class 类的实例对象
Integer integer = new Integer(1);
System.out.println(integer instanceof Integer);//true
这没什么好说的,最普遍的一种用法。
- obj 为 class 接口的实现类
- 了解Java 集合的,我们知道集合中有个上层接口 List,其有个典型实现类 ArrayList
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
所以我们可以用 instanceof 运算符判断 某个对象是否是 List 接口的实现类,如果是返回 true,否则返回 false
ArrayList arrayList = new ArrayList();
System.out.println(arrayList instanceof List);//true
或者反过来也是返回 true
List list = new ArrayList();
System.out.println(list instanceof ArrayList);//true
- obj 为 class 类的直接或间接子类
我们新建一个父类 Person.class,然后在创建它的一个子类 Man.class
public class Person {
}
Man.class
public class Man extends Person{
}
测试:
Person p1 = new Person();
Person p2 = new Man();
Man m1 = new Man();
System.out.println(p1 instanceof Man);//false
System.out.println(p2 instanceof Man);//true
System.out.println(m1 instanceof Man);//true
注意第一种情况, p1 instanceof Man ,Man 是 Person 的子类,Person 不是 Man 的子类,所以返回结果为 false。