Home > Enterprise >  How to use child as constructor parameter?
How to use child as constructor parameter?

Time:12-25

I want to be able to say Parent p = new Parent(child);, in I way that works like

public class Creature extends Egg {
    public Creature hatch(Egg egg) {
        Creature out = (Creature) egg;
        out.potency = new Random().nextDouble();
        return out;
    }
}

But I can't get this to work in a constructor, as I cannot do this = (Creature)egg because this may not be directly assigned.
I could of course copy all variables from egg to this, but I would rather not have to modify the constructor every time I change a variable in Egg.

Does anyone know how to easily copy all data from a child class to a parent class 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;
    }
}
  • Related