I want to be able to write something like this Subclass sub = new Subclass(parent);
.
Here's a pseudocode illustrating the idea
public class Creature extends Egg {
public Creature hatch(Egg egg) {
Creature out = (Creature) egg;
out.potency = new Random().nextDouble();
return out;
}
}
It's not possible to make it work exactly like this.
I could of course copy all variables from egg
to this
(instance of Creature
), but I don't want to modify the constructor every time I change variables in Egg
class.
What would be the easiest way to copy all data from a Parent class instance to a Subclass in a constructor?
CodePudding user response:
That a good use case for Composition, not for Inheritance. I.e. instead of extending Egg
class, you can introduce a property of type Egg
in the Creature
class, and refer to it when you need a property that is coming from the egg.
Keep in mind, that although Inheritance is an important principle of the OOP, the Composition should be always considered as a preferred approach (for more information refer to the item Favor composition over inheritance of the classic book "Effective Java" by Joshua Bloch, former Sun-employee, author of the Collections framework, and many other language features).
Also, since from the logical standpoint only one Creature can be hatched from one Egg you can introduce boolean
property hatched
in the Egg
class to ensure that the same Egg can not be reused to spawn multiple Creatures.
Here's how it might be implemented:
public class Creature {
private Egg egg;
private double potency;
private Creature(Egg egg) {
this.egg = egg;
}
public Creature hatch(Egg egg) {
if (egg.isHatched()) throw new IllegalStateException("This egg has been already hatched");
egg.setHatched(); // marking the egg as hatched
Creature out = new Creature(egg); // hatching the creature
out.potency = new Random().nextDouble();
return out;
}
}
public class Egg {
private boolean hatched;
// some other properties
public void setHatched() {
this.hatched = true;
}
public boolean isHatched() {
return hatched;
}
}