在java中使用“实例”‘instanceof’操作符是用来做什么的?我了解到Java有instanceof接线员。你能详细说明一下它在哪里使用吗?它的优点是什么?
3 回答
凤凰求蛊
TA贡献1825条经验 获得超4个赞
public void doSomething(Number param) { if( param instanceof Double) { System.out.println("param is a Double"); } else if( param instanceof Integer) { System.out.println("param is an Integer"); } if( param instanceof Comparable) { //subclasses of Number like Double etc. implement Comparable //other subclasses might not -> you could pass Number instances that don't implement that interface System.out.println("param is comparable"); }}
慕田峪9158850
TA贡献1794条经验 获得超7个赞
instanceof
class A { } class C extends A { } class D extends A { } public static void testInstance(){ A c = new C(); A d = new D(); Assert.assertTrue(c instanceof A && d instanceof A); Assert.assertTrue(c instanceof C && d instanceof D); Assert.assertFalse(c instanceof D); Assert.assertFalse(d instanceof C);}
添加回答
举报
0/150
提交
取消