Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - is there a "subclassof" like instanceof?

Im overriding an equals() method and I need to know if the object is an instance of a Event's subclass (Event is the superclass). I want something like "obj subclassof Event". How can this be made?

Thanks in advance!

like image 670
rasgo Avatar asked Apr 23 '10 15:04

rasgo


People also ask

What can I use instead of Instanceof in Java?

Having a chain of "instanceof" operations is considered a "code smell". The standard answer is "use polymorphism".

Does Java have Instanceof?

The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type. It returns either true or false.

What is the difference between getClass and Instanceof?

Coming to the point, the key difference between them is that getClass() only returns true if the object is actually an instance of the specified class but an instanceof operator can return true even if the object is a subclass of a specified class or interface in Java.

Does Instanceof check subclass?

By default instanceof checks if an object is of the class specified or a subclass (extends or implements) at any level of Event.


2 Answers

instanceof can handle that just fine.

like image 171
Ken Bloom Avatar answered Sep 26 '22 14:09

Ken Bloom


With the following code you can check if an object is a class that extends Event but isn't an Event class instance itself.

if(myObject instanceof Event && myObject.getClass() != Event.class) {     // then I'm an instance of a subclass of Event, but not Event itself } 

By default instanceof checks if an object is of the class specified or a subclass (extends or implements) at any level of Event.

like image 22
Adrian Avatar answered Sep 22 '22 14:09

Adrian