简体   繁体   中英

Java get runtime class of this?

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?

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.

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

this.getClass()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM