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
AnimalDog
dog instanceof Cat // does not even compile!
DogCat
dogObjectinstanceof
expressionThatIsNull instanceof TT.
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
添加回答
舉報
