Home> Java> javaTutorial> body text

The role of instanceof in java

下次还敢
Release: 2024-05-01 18:06:50
Original
715 people have browsed it

The instanceof operator in Java is used to check whether an object belongs to a specific class or its subclass. It accepts an object reference and a class object, and returns true or false according to whether the object belongs to the class or its subclass. Commonly used on type checking, polymorphism, and class hierarchies.

The role of instanceof in java

The role of instanceof operator in Java

The instanceof operator is a binary operator used to check Whether an object belongs to a specific class or its subclasses. It receives two operands: an object reference and a class object.

Syntax

boolean instanceofResult = objectReference instanceof classObject;
Copy after login

Return value

If objectReference belongs to classObject or its subclass, the instanceof operator returns true; otherwise Return false.

Usage scenarios

The instanceof operator is usually used in the following scenarios:

  • Type checking:Determine an object Belongs to a specific class so that it can be processed appropriately.
  • Polymorphism:In polymorphic methods, different behaviors are performed based on the actual type of the object.
  • Class Hierarchy:Checks whether an object belongs to a class in a specific class hierarchy.

Instance

The following are some examples of the instanceof operator:

Object object = new Object(); boolean isObject = object instanceof Object; // true Animal animal = new Dog(); boolean isDog = animal instanceof Dog; // true boolean isAnimal = animal instanceof Animal; // true
Copy after login

It should be noted that the instanceof operator only checks the object's actual type without checking its declared type. Therefore, the following code returns true even though the object variable is declared as type Object:

Object object = new String(); boolean isObject = object instanceof Object; // true boolean isString = object instanceof String; // true
Copy after login

By using the instanceof operator, you can efficiently check the type of an object and perform appropriate operations in your code.

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

source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!