3 回答

TA貢獻(xiàn)1963條經(jīng)驗(yàn) 獲得超6個(gè)贊
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貢獻(xiàn)1890條經(jīng)驗(yàn) 獲得超9個(gè)贊
instanceof
if (obj instanceof Checkbox){ Checkbox cb = (Checkbox)obj; boolean state = cb.getState();}

TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超8個(gè)贊
這個(gè) instanceof
運(yùn)算符可用于測試對象是否為特定類型. if (objectReference instanceof type)
一個(gè)簡單的例子: String s = "Hello World!"return s instanceof String;//result --> true
然而,申請 instanceof
在空引用變量/表達(dá)式上返回false。 String s = null;return s instanceof String;//result --> false
由于子類是其超類的“類型”,所以可以使用 instanceof
來驗(yàn)證這個(gè).。 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
添加回答
舉報(bào)