1

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?

AdjustingForInflation
  • 1,571
  • 2
  • 26
  • 50

2 Answers2

5

You could use the instanceof operator: What is the 'instanceof' operator used for?

Bear in mind that doing things the way you're asking will require Animal to know about all of its subclasses (direct and otherwise). This clearly does not scale and invites maintenance problems.

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • The method should be overridden in the necessary classes instead of using `instanceof` per subclass. – Luiggi Mendoza Feb 19 '14 at 20:41
  • Ok, very odd request. Well, `instanceof` can do it assuming `Dog` and the other classes (`Worlf`, `Leopard`, etc.) don't have subclasses as well, otherwise it might be better using `this.getClass().equals(Dog.class)` and on... – Luiggi Mendoza Feb 19 '14 at 20:45
  • @LuiggiMendoza: A complete nightmare for sure. But that's what the OP is asking... – NPE Feb 19 '14 at 20:46
  • Thanks all - I'm going with Luiggi's suggestion because there are several levels of inheritance going on here. **Trust me**, this isn't how I want to code... – AdjustingForInflation Feb 19 '14 at 21:05
  • @TotesMcGotes we're all curious of the constraint that is disallowing you from using OO concepts in an OO language. Care to share? – Cruncher Feb 19 '14 at 21:13
3

To get the runtime class use getClass(). It will return the sub-class even though the code is in the super-class.

this.getClass()
Ted Bigham
  • 4,237
  • 1
  • 26
  • 31