Reputation: 119
I have hierarchy of few classes: Organism -> Fox,Antelope,Wolf
And i want to create a method that will define what is the class of the given object, without returning new instance of this object.
Something like this:
public Organism defineOrganismClass(Organism o) {
if (o instanceof Antelope) {
return ...;
}if (o instanceof Fox) {
return ...;
} //and so on
}
Is there a way to do it?
Upvotes: 0
Views: 598
Reputation: 93968
Yes, you can return Class<? extends Organism>
instead, e.g. Fox.class
. This will give you the class definition, but no instance. You would not need the if
statements, just return o.getClass()
.
It does of course beg the question what you then want to do with that class. Maybe you want to define an enum instead, e.g. enum OrganismType { ANTELOPE, FOX }
which is easier to operate on.
Upvotes: 1