Java instanceof Operator: Checking Object Types
The 'instanceof' operator in Java is used to determine whether an object is an instance of a specific class or implements a particular interface. It returns 'true' if the object is an instance of the specified class or implements the specified interface, and 'false' otherwise.
Here's the syntax for using the 'instanceof' operator:
object instanceof Class/Interface
For example, let's say we have a class called 'Person' and an object called 'personObj'. We can use the 'instanceof' operator to check if 'personObj' is an instance of the 'Person' class:
if (personObj instanceof Person) {
// Code to be executed if personObj is an instance of Person
} else {
// Code to be executed if personObj is not an instance of Person
}
The 'instanceof' operator is a valuable tool for type checking in Java, allowing you to write more robust and flexible code.
原文地址: https://www.cveoy.top/t/topic/fTC3 著作权归作者所有。请勿转载和采集!