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!
Having a chain of "instanceof" operations is considered a "code smell". The standard answer is "use polymorphism".
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.
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.
By default instanceof checks if an object is of the class specified or a subclass (extends or implements) at any level of Event.
instanceof
can handle that just fine.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With