📅  最后修改于: 2023-12-03 14:59:57.914000             🧑  作者: Mango
instanceof
Codegrepper Java instanceof
is a powerful feature that allows you to determine whether an object is an instance of a particular class or interface. This is very useful when you need to perform different actions depending on the type of object that you are working with.
object instanceof class/interface
Where object
is the object that you want to test, and class/interface
is the class or interface that you want to test against.
Object obj = new Integer(100);
if (obj instanceof Integer) {
System.out.println("Object is an instance of Integer");
} else {
System.out.println("Object is not an instance of Integer");
}
In this example, we create a new Integer
object and assign it to the obj
variable. We then use the instanceof
operator to test whether obj
is an instance of the Integer
class. Since obj
is an instance of Integer
, the output of this example is:
Object is an instance of Integer
instanceof
with InterfacesYou can also use the instanceof
operator to test whether an object implements a particular interface. For example:
interface MyInterface {
void doSomething();
}
class MyClass implements MyInterface {
public void doSomething() {
// implementation here
}
}
MyInterface obj = new MyClass();
if (obj instanceof MyInterface) {
System.out.println("Object implements MyInterface");
}
In this example, we define an interface called MyInterface
and a class called MyClass
that implements the interface. We then create a new MyClass
object and assign it to the obj
variable, which is declared to be of type MyInterface
. We use the instanceof
operator to test whether obj
implements the MyInterface
interface. Since obj
does implement MyInterface
, the output of this example is:
Object implements MyInterface
Codegrepper Java instanceof
is a powerful feature that can help you to write more flexible and reusable code. By using instanceof
, you can determine the type of object that you are working with and perform different actions depending on its type.