Sobes.tech
Junior — Middle

Mis on instanceof operaatori eesmärk Java-s ja kuidas seda kasutatakse objekti tüübi määramiseks?

sobes.tech AI

Vastus AI-lt

In Java, the instanceof operator is used to check whether an object is an instance of a specific class or its subclasses.

It returns true if the object belongs to the specified type, and false otherwise.

Example usage:

class Animal {}
class Dog extends Animal {}

Animal animal = new Animal();
Dog dog = new Dog();

System.out.println(animal instanceof Animal); // true
System.out.println(dog instanceof Animal);    // true, because Dog inherits from Animal
System.out.println(animal instanceof Dog);    // false

This is useful when you want to perform different actions depending on the actual type of the object at runtime.