Is there a way to determine what type a class is an instance of in Java?

后端 未结 5 2101
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-12 04:11

Say I have 3 classes like so:

class A {}
class B extends A {}
class C extends A {}

Would it then be possible to determine whether a particu

5条回答
  •  醉酒成梦
    2020-12-12 04:43

    There is the instanceof operator that does what you want, as others have answered.

    But beware that if you need something like this, it's a sign that there might be a flaw in the design of your program. The better, more object oriented way to do this is by using polymorphism: put a method in the superclass A, override that method in B and C, and call the method on myObject (which should have type A):

    A myObject = ...;  // wherever you get this from
    
    // Override someMethod in class B and C to do the things that are
    // specific to those classes
    myObject.someMethod();
    

    instanceof is ugly and should be avoided as much as possible, just like casting is ugly, potentially unsafe and should be avoided.

提交回复
热议问题