3 回答
TA贡献1963条经验 获得超6个赞
instanceof
interface Domestic {}class Animal {}class Dog extends Animal implements Domestic {}class Cat extends Animal implements Domestic {}
dog
对象Object dog = new Dog()
dog instanceof Domestic // true - Dog implements Domesticdog instanceof Animal // true - Dog extends Animaldog instanceof Dog // true - Dog is Dogdog instanceof Object // true - Object is the parent type of all objects
Object animal = new Animal();
,
animal instanceof Dog // false
Animal
Dog
dog instanceof Cat // does not even compile!
Dog
Cat
dog
Object
instanceof
expressionThatIsNull instanceof T
T
.
TA贡献1890条经验 获得超9个赞
instanceof
if (obj instanceof Checkbox){ Checkbox cb = (Checkbox)obj; boolean state = cb.getState();}
TA贡献1860条经验 获得超8个赞
这个 instanceof
运算符可用于测试对象是否为特定类型. if (objectReference instanceof type)
一个简单的例子: String s = "Hello World!"return s instanceof String;//result --> true
然而,申请 instanceof
在空引用变量/表达式上返回false。 String s = null;return s instanceof String;//result --> false
由于子类是其超类的“类型”,所以可以使用 instanceof
来验证这个.。 class Parent { public Parent() {}}class Child extends Parent { public Child() { super(); }}public class Main { public static void main(String[] args) { Child child = new Child(); System.out.println( child instanceof Parent ); }}//result --> true
添加回答
举报