// instanceof 运算符
package yunsuanfu;
// 定义 IBase 接口
interface IBase {
public void print();
}
// 定义 Derive 类实现 IBase 接口
class Derive implements IBase {
int b;
public Derive(int b){
this.b = b;
}
public void print(){
System.out.println("In Derive!");
}
}
// 定义 Derive 的子类 Derive1
class Derive1 extends Derive {
int c;
public Derive1(int b,int c){
super(b);
this.c = c;
}
public void print(){
System.out.println("In Derive1!");
}
}
public class InstanceofDemo{
// 判断对象类型
public static void typeof(Object obj){
if(obj instanceof Derive){
Derive derive = (Derive) obj;
derive.print();
}else if(obj instanceof Derive1){
Derive1 derive1 = (Derive1) obj;
derive1.print();
}
}
public static void main(String[] args){
IBase b1 = new Derive(4);
IBase b2 = new Derive1(4,5);
System.out.print("b1 is ");
// 调用 typeof() 判断b1对象类型
typeof(b1);
System.out.print("b2 is ");
// 调用 tyoeof() 判断b2对象类型
typeof(b2);
}
}
//大多数情况下不推荐使用 instanceof 实现方法的动态调用机制,
//使用 instanceof 会产生大量代码冗余,建议利用类的多态
















