1

I have the main class

public class Main(){
   public static void main(String[] args){
      ArrayList<A> as = new ArrayList<>();
      C c = new C();
      D d = new D();
      E e = new E();

      as.add(c);
      as.add(d);
      as.add(e);

      for(A a : as){
         a.print(); // want to do it conditionally when Object inside list have extended class B
      }
   }
}

Method print() is extended from an abstract class A. Classes C and D extends class B and B extends A.

    A
  /   \
  B    E
 / \
C   D

How can I do this approach?

Tried:

for(A a : as){
   if(a.getClass().getSuperclass().getSimpleName().equals("B")){
      a.print(); // Doesn't work a.getClass().getSuperclass().getSimpleName() prints A
   }
}

Any tip to achieve this?

azro
  • 53,056
  • 7
  • 34
  • 70
Rancio
  • 155
  • 1
  • 3
  • 15
  • use instanceof as in `if (a instanceof B)` – Joakim Danielson Aug 08 '18 at 12:12
  • What are you actually trying to solve with this (i.e. why do you need the class name)? Having to use `instanceof` could mean that the design needs improving. – Mick Mnemonic Aug 08 '18 at 12:17
  • When you have a problem, try to find the real source of problem, it's not "get the name of an abstract parent class", but "know if an object extends a class ;) – azro Aug 08 '18 at 12:30

1 Answers1

7

You can use instanceof:

for(A a : as){
    if(a instanceof B){
        a.print();
    }
}

For more information see this question.

Lino
  • 19,604
  • 6
  • 47
  • 65