Skip to main content
1 of 3
SkyWalker
  • 29.3k
  • 14
  • 77
  • 134

Here the instanceof operator comes into use. If you want a data store with multiple types it is good to use the abstract class as the generic.

abstract class Carpet { } class CircleCarpet extends Carpet { } class RectCarpet extends Carpet { } ArrayList<Carpet> carpets = new ArrayList<Carpet>(); carpets.add(new CircleCarpet()); carpets.add(new RectCarpet()); ... carpets.add( new CircleCarpet() ); ... for( Carpet c : carpets ) { if( c instanceof CircleCarpet ) System.out.printline( c.getRadius() ); } 

Note: that the is vital. Without it, you must cast to the carpet you want -- otherwise you get the hashcode of the object.

ArrayList carpets = new new ArrayList(); for( Carpet c : carpets ) { if( c instanceof CircleCarpet ) { CircleCarpet cc = (CircleCarpet)c; cc.getRadius(); } } 
SkyWalker
  • 29.3k
  • 14
  • 77
  • 134