/* * Person.java 1.0 * * Example for OOP * */ class Person implements Cloneable{ public Car car; private String name; public Person (String name){ this.name = name; } public String toString(){ return name; } /* pre: car.owner = this */ public void setCar(Car car){ this.car = car; } public Car getCar(){ return car; } /* Exercise 4 * First remember to implement the interface Cloneable A simple solution is to make the cloned person NOT own a car. This is what is done below. An other solution is to say one cannot clone persons who owns a car. Also, we provide the clone with a clone of the car. */ public Object clone() { try { Person p = (Person) super.clone(); p.car = null; return p; } catch(CloneNotSupportedException e) { throw new Error(e); } } // Clone test public static void main(String[] args) { Person p1 = new Person("Lars"); Car c = new Car(p1,"Skoda"); Person p2 = (Person) p1.clone(); System.out.println( p1.getCar() ); System.out.println( p2.getCar() ); System.out.println( "and owners" ); System.out.println( p1.getCar().getOwner() ); // Lars System.out.println( p2.getCar() ); // null } }