Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example of ´instanceof´

Tags:

public class TableModel2 extends TableModel1 { ... }  TableModel2 tableModel = new TableModel2();  boolean t1 = tableModel instanceof TableModel1; boolean t2 = tableModel instanceof TableModel2; 

In the above example, t1 and t2 are true. So, how could I differentiate between TableModel1 and TableModel2 using instanceof?

like image 883
Klausos Klausos Avatar asked Feb 07 '12 10:02

Klausos Klausos


People also ask

What is an Instanceof?

instanceof is a binary operator we use to test if an object is of a given type. The result of the operation is either true or false. It's also known as a type comparison operator because it compares the instance with the type. Before casting an unknown object, the instanceof check should always be used.

What is instance of operator explain with an example?

The instanceof operator in Java is used to check whether an object is an instance of a particular class or not. objectName instanceOf className; Here, if objectName is an instance of className , the operator returns true . Otherwise, it returns false .

What is Instanceof keyword?

instanceof is a keyword that is used for checking if a reference variable is containing a given type of object reference or not. Following is a Java program to show different behaviors of instanceof.

What is Instanceof an example of PHP?

Definition and Usage The instanceof keyword is used to check if an object belongs to a class. The comparison returns true if the object is an instance of the class, it returns false if it is not.


1 Answers

You cannot do it with instanceof, but you can do it with getClass:

boolean t1 = tableModel.getClass().equals(TableModel1.class); boolean t2 = tableModel.getClass().equals(TableModel2.class); 

The instanceof operator is intended for checking class hierarchy all the way, down to the java.lang.Object, including the checks for all interfaces. It lets you know if an instance of the object you have can be cast to the type you specified without triggering class cast exception.

getClass, on the other hand, returns the specific class of the given object.

like image 156
Sergey Kalinichenko Avatar answered Oct 13 '22 23:10

Sergey Kalinichenko