3
Hello,
I have the following situation, I have an Animal object and I want to evolve it into a Puppy:
public class Animal {
private boolean alive = true;
public boolean isAlive() {
return alive;
}
public void setAlive(boolean alive) {
this.alive = alive;
}
}
public abstract class Mamifero extends Animal {
public abstract void mamar();
}
public class Cachorro extends Mamifero {
@Override
public void mamar() {
System.out.println("Done");
}
}
I know this (below) does not work:
Animal meuAnimal = new Animal();
Cachorro cao = (Cachorro) meuAnimal;
But I don’t want to have to instantiate a Puppy and go attribute-to-attribute by filling it with the N data that my Animal has.
Is there any way to make this evolution automatically?
I’m not sure I understand what you want. If you are instantiating one
Cachorro
in a certain way is instantiating aAnimal
. In any case you will have to put the data into the object. You can create a routine that does this or you can create values default for members if this is possible (you did this in this short code). In some cases a constructor may be required to start these values default. But the question doesn’t make it very clear what you want.– Maniero
I possess an animal object (brute), because the class that instigated it is unable to specialize it. After treating this Animal I define that it should be a Dog, so I want to specialize it?
– Gleison
I think the "less worse" option would be to create an animal builder who receives an animal as a parameter. So when you convert it to other animals, you would do something like:
Cachorro cao = new Cachorro(animal);
And regardless of what kind of animal you instantiated you would only need to keep sending the animal(parameter) to the Animal class.– Christian Beregula
Animal meuAnimal = new Cachorro();
but you can only use the methods present in the Animal class– David Schrammel
@Christianberegula you will answer?
– Maniero
You are experiencing a typical problem caused by the use of inheritance by yourself and not to solve a real problem: the promotion of an existing object to a more specialized type object. There is no such thing in practice - a dog is born a dog, it is not born an undefined type of animal to turn into a dog later on. The same is true in modeling a real problem in a real domain - if you notice the need to promote an object to a type below in the hierarchy, it’s because you used inheritance when you shouldn’t have.
– Caffé