Reputation: 2930
I would like to create a copy of an object that contains a super class of another object. In this example I want to make a copy of the Box
that contains a Toy
. But all kind of toys can be in the box. What would be the best way to create the copy constructor in Toy
?
class Box {
Toy toy;
public Box(Toy toy) {
this.toy = toy;
}
public Box(Box box) {
this.toy = new Toy(box.getToy());
}
}
abstract class Toy {
public Toy(String name) {
// ...
}
}
class Car extends Toy {
public Car(String name) {
super(name);
// ...
}
}
class Puppet extends Toy {
public Puppet(String name) {
super(name);
// ...
}
}
I don't really have an idea how to approach this problem.
Upvotes: 1
Views: 158
Reputation: 1332
i think this structure can help you to have an idea,in this case we pass an Object toy using Box Constructor to SuperClass(Toy) and in Toy Class we have a Constructor to Accept an Object from Toy Class then it's call getInstance Method for Initialize toy object(just for example).
class Box extends Toy
{
public Box(Toy toy)
{
super(toy);
}
}
Class Toy
{
private static Toy toys = new Toy();
Toy(){}
Toy(Toy toy)
{
toy = Toy.getInstance();
}
public static Toy getInstance()
{
return toys;
}
}
and either,if you don't want other Classes(sub class) to don't see a specified methods and attributes just make them private,and if you want sub classes haven't access to set and get methods too,make them private only!
Upvotes: 0
Reputation: 37645
Make Toy
have an abstract method copy()
with return type Toy
. Then you will be forced to override this in Car
and Puppet
. In the copy constructor for Box
you can use box.getToy().copy()
.
Upvotes: 6
Reputation: 25950
You can override the clone method of each Toy
's subclass and then :
public Box(Box box) {
this.toy = (Toy) box.getToy().clone();
}
Alternatively, if you have a constant number of types of toy, you can use an enumeration instead of a class.
Upvotes: 1