Refactor Java using inheritance between subclass and superclass

  • A+
Category:Languages

I would like refractor some code using the inheritance between my superclasse and subclasses.

He are my classes:

public class Animal {     int a;     int b;     int c; }  public class Dog extends Animal {     int d;     int e; }  public class Cat extends Animal {     int f;      int g; } 

There is my current code:

ArrayList<Animal> listAnimal = new ArrayList();  if (condition) {     Dog dog = new Dog();     dog.setA(..);     dog.setB(..);     dog.setC(..);     dog.setD(..);     dog.setE(..);        listAnimal.add(dog);  } else {     Cat cat = new Cat();     cat.setA(..);     cat.setB(..);     cat.setC(..);     cat.setF(..);     cat.setG(..);     listAnimal.add(cat); } 

I would like refractor the commons attributes. I know this doesn't work. I could use constructor in subclass for create an instance with Animal class in parameter, but it doesn't use inheritance... I would like something like that:

Animal animal = new Animal(); animal.setA(..); animal.setB(..); animal.setC(..);  if (condition) {     Dog anim = (Dog) animal; //I know it doesn't work     anim.setD(..);     anim.setE(..);   } else {     Cat anim = (Cat) animal; //I know it doesn't work     anim.setF(..);     anim.setG(..); }  listAnimal.add(anim); 

Is there any solution to achieve something like this ?

 


Your idea to have a variable of type Animal is good. But you also have to make sure to use the right constructor:

Animal animal;  if (condition) {     Dog dog = new Dog();     dog.setD(..);     dog.setE(..);       animal = dog; } else {     Can cat = new Cat();      cat.setF(..);     cat.setG(..);     animal = cat; }  animal.setA(..); animal.setB(..); animal.setC(..);  listAnimal.add(animal); 

Hint: If an Animal is always either Cat or Dog consider making Animal abstract. Then the compiler will automatically complain whenever you try to do new Animal().

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: