I have a superclass and child classes.
I am in a child class and in a super method I want to check if a certain parameter object is of the certain child class.
I want something like
if (MyObj instanceof this)
what is the most efficient way to do it?
I know I can do
if (MyObj.getClass.equals(this.getClass)
But that isnt too eficient
Referencing subclasses in superclass methods is indicative of a design problem in need of refactoring. While you can do it (
if (this instanceof SubClass)), it tightly couples the superclass to the subclass(es). In class-based OOP, subclasses are of course tightly coupled to the superclass (inheriting is inherently tightly-coupling), but the converse is rarely true and almost never appropriate.In terms of efficiency,
if (this instanceof SomeClass)is fine.Edit: From your edit, it almost seems like you’re trying to find out in the superclass’s method whether it’s being called on an instance whose final run-time class is the superclass, and not a subclass. That’s a slightly different thing, and AFAIK the most efficient way to do it pretty much as you’ve quoted:
It still suggests that the class wants to be refactored a bit, though.
Edit 2: But from your comment on the question, it sounds like you want to compare it with the class of a member you’re holding. If the member is an instance of the class itself, use the above. If it may vary, then: