Reputation: 165
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?
Upvotes: 1
Views: 104
Reputation: 19926
You can use instanceof
:
for(A a : as){
if(a instanceof B){
a.print();
}
}
For more information see this question.
Upvotes: 7