<<< Cloneable Object implementation | Index | >>> |
Cloning is a potentially dangerous action, because it can cause unintended side effects.
For example, if the object being cloned contains a field referencing another object, then, after the clone is made, the field in the clone refers to the same object as does the field in the original.
Copy constructors provide an attractive alternative to the Object.clone():
public class Book extends Product implements Printable
{
public static void main (String[] args )
{
Book first = new Book( "12345", "Irish stories and legends", 14.50, "folklore" );
Book second = new Book( first );
first.print();
second.print();
}
private String author;
// Constructor
public Book(
String code,
String description,
double price,
String author )
{
super( code, description, price );
this.author = author;
}
// Copy constructor.
public Book( Book another )
{
this( another.code, another.description, another.price, another.author );
}
// implement the Printable interface
@Override
public void print()
{
System.out.println(
"Code: " + code);
System.out.println(
"Description: " + description);
System.out.println(
"Price: " + price);
System.out.println(
"Autor: " + author);
}
}//class Book
For complete example, see CIS-257 Java Samples
<<< Cloneable Object implementation | Index | >>> |