user2865715 user2865715 - 5 months ago 25
Java Question

Clone a single tone object

Here is the listing below:



public class Car {
private static Car car = null;

private void car() {
}

public static Car GetInstance() {
if (car == null) {
car = new Car();
}
return car;
}

public static void main(String arg[]) throws CloneNotSupportedException {
car = Car.GetInstance();
Car car1 = (Car) car.clone();
System.out.println(car.hashCode());// getting the hash code
System.out.println(car1.hashCode());
}
}



Why do this code throw cloneNotSupportedException?

Answer
public class Car implements Cloneable {
    private static Car car = null;

    public static Car GetInstance() {
        if (car == null) {
            car = new Car();
        }
        return car;
    }

    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

Car car = Car.GetInstance();
Car car1 = (Car) car.clone();
System.out.println(car.hashCode());
System.out.println(car1.hashCode());

Output:

1481395006
2027946171