如何判断一个对象是否是俩一个类的实例?

来源:百度知道 编辑:UC知道 时间:2024/07/02 10:11:36
假如有基类A 分别派生了B、C而B、C中又各自假如了一些新的方法。
假设有方法 methed(A a){//传了的是B或者是C的实例
//我该在这里如何判断出a是B的实例或是C的实例。
}
要一个通用的解决办法,非常感谢!
class AForm extends ActionForm
class BForm extends ActionForm

AForm af = new AForm();
BForm bf = new BForm();
if(bf instanceof AForm )
System.out.println("True");
报错啊Incompatible conditional operand types BForm and AForm
为什么这么写就报错呢?

if(a instanceof B)
{
//...
}

AForm af = new AForm();
BForm bf = new BForm();
if(bf instanceof AForm )
编译器自己进行了判断,实际上你要用的时候可能是这样的:

ActionForm是由容器创建的,当你得到时都是ActionForm类,
ActionForm af = new AForm();
ActionForm bf = new BForm();
if(bf instanceof AForm )