How to avoid casting of a Parent's field in subclasses

Question

My Parent class is like this:

public abstract class Parent{

  protected HashMap<String, Foo> field;
  public abstract void method1();
}

Now, the two children of Parent class need to iterate through the HashMap to do something. The first child needs the Foo class, so there's no problem. The second child, though, has method1() implemented like this:

@Override
public void method1(){
  for(Foo i : this.field.values(){
    ((Bar) i).specificMethod();
    /* other code */
  }
}

with Bar that extends Foo, of course. As you can see, a cast is mandatory to use the specific method of the Bar class. Can this be avoided is some way? I know I could use Generics in Parent class like this:

public abstract class Parent<T extends Foo>{

  protected HashMap<String, T> field;
  /* etc. */
}

but I don't know if this is considered bad behavior.


Show source
| generics   | java   | inheritance   | casting   2016-12-29 16:12 2 Answers

Answers to How to avoid casting of a Parent&#39;s field in subclasses ( 2 )

  1. 2016-12-29 16:12

    The child class already has an intimate knowledge of the contents of the map. Casting, as you mentioned, is a ugly and dodgy approach. Moving this declaration to the generic specification of the class makes it much more obvious, and would probably be the right way to go.

  2. 2016-12-29 16:12

    Your foo class should have a method which bar will override.....so in all cases you will call

    i.execute()

    where execute is a method in foo which will be override by subclasses....doing this would remove the need to explicitly cast the object to the sub class type.

Leave a reply to - How to avoid casting of a Parent's field in subclasses

◀ Go back