Home  >  Article  >  What does instanceof mean in java

What does instanceof mean in java

尊渡假赌尊渡假赌尊渡假赌
尊渡假赌尊渡假赌尊渡假赌Original
2023-11-13 13:52:001353browse

In Java, instanceof is a binary operator used to check whether an object is an instance of a class or an instance of a subclass of a class. Its syntax is "object instanceof class". Among them, object is an object reference, and class is a class name or interface name.

What does instanceof mean in java

# Operating system for this tutorial: Windows 10 system, Dell G3 computer.

In Java, instanceof is a binary operator used to check whether an object is an instance of a class or an instance of a subclass of a class.

The syntax is:

object instanceof class

where object is an object reference and class is a class name or interface name.

The function of the instanceof operator is to determine whether object is an instance of class or a derived class of class. If so, returns true; otherwise returns false.

The following is a simple example:

class Animal {
    // ...
}
class Dog extends Animal {
    // ...
}
public class Main {
    public static void main(String[] args) {
        Animal animal = new Dog();
        System.out.println(animal instanceof Animal); // 输出 true
        System.out.println(animal instanceof Dog);    // 输出 true
    }
}

In the above example, animal is an instance of the Dog class and is also an instance of the Animal class, so animal instanceof Animal and animal instanceof Dog both return true.

The instanceof operator is often used for type checking in actual development, especially when dealing with polymorphism.

The above is the detailed content of What does instanceof mean in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn