Say I have the following object hierarchy:
public abstract class Animal {
...
}
public class Canine extends Animal {
...
}
public class Feline extends Animal {
...
}
public class Dog extends Canine {
...
}
public class Wolf extends Canine {
...
}
public class Leopard extends Feline {
...
}
Let's say the Animal
class has a final method that needs to take different actions depending on what the object's runtime type/class is:
public abstract class Animal {
// Lots of stuff blah blah blah
public final makeNoise() {
// If we're a Dog, then System.out.println("Woof!");
// Else if we're a Wolf, then System.out.println("Gggrrrrr!");
// etc.
}
}
Here's the kicker: I know that best practices and OOP would have me write makeNoise()
to be an abstract method, and then just implement a different version in each subclass. However, for reasons outside the scope of this question, I can't do that.
So, barring best OOP practices, how can I tell - from inside the parent makeNoise()
method - what our runtime class is?