how to get the type of a child class?

edited October 2014 in Programming Questions

Here's an example

class A
{
  A() {
  }
}

class B extends A
{
  B() {
  }
}

class C extends A
{
  C() {
  }
}

void draw()
{
  A obj;
  if (random(0, 1) > .5)
    obj = new B();
  else
    obj = new C();

   //what type is obj?
}

How can I tell what type object "obj" is?

Answers

  • println(obj.getClass().getSimpleName());

  • edited October 2014 Answer ✓

    Here are 2 other ways to test the type of class.

    void setup() {
      size(440,200);
      frameRate(10);
    }
    
    void draw()
    {
      background(255);
      fill(0);
      A obj;
      if (random(0, 1) > .5)
        obj = new B();
      else
        obj = new C();
    
      if (obj.getClass() == A.class) // always false
        text("B class object", 20, 20);
      if (obj.getClass() == B.class)
        text("B class object", 20, 40);
      if (obj.getClass() == C.class)
        text("C class object", 20, 60);
    
      if (obj instanceof A)  // Always true
        text("Instance of A", 220, 20);
      if (obj instanceof B)
        text("Instance of B", 220, 40);
      if (obj instanceof C)
        text("Instance of C", 220, 60);
    }
    

    Notice that the instanceof operator also recognises the object's parent class.

  • Thank you!

Sign In or Register to comment.