instanceofparola chiave è un operatore binario utilizzato per verificare se un oggetto (istanza) è un sottotipo di un determinato Tipo.
Immaginare:
interface Domestic {}
class Animal {}
class Dog extends Animal implements Domestic {}
class Cat extends Animal implements Domestic {}
Immagina un dog oggetto , creato con Object dog = new Dog(), quindi:
dog instanceof Domestic // true - Dog implements Domestic
dog instanceof Animal // true - Dog extends Animal
dog instanceof Dog // true - Dog is Dog
dog instanceof Object // true - Object is the parent type of all objects
Tuttavia, con Object animal = new Animal();,
animal instanceof Dog // false
perché Animalè un supertipo Doge forse meno "raffinato".
E,
dog instanceof Cat // does not even compile!
Questo perché Dognon è né un sottotipo né un supertipo di Cat, e inoltre non lo implementa.
Si noti che la variabile utilizzata per dogsopra è di tipo Object. Questo per mostrare instanceofè un'operazione di runtime e ci porta a un / il caso d'uso: reagire in modo diverso sulla base di un tipo di oggetti in fase di runtime .
Cose da notare: expressionThatIsNull instanceof Tè falso per tutti i tipi T.
Buona codifica.