Hi Everyone,
I came up with this solution here:
@Override
public Object clone() throws CloneNotSupportedException {
if(this instanceof B && !(this instanceof C)) return new CloneNotSupportedException();
return super.clone();
}
During testing it works fine but it won't pass the validator. I wonder if there is a test case in which it won't work? Is this solution just wrong? Or maybe it's too specific to this particular case and a more general solution would be better? Any help would be greatly appreciated to understand why it doesn't work.
Thanks in advanced!package com.codegym.task.task21.task2109;
/*
Prevent cloning
*/
public class Solution {
public static class A implements Cloneable {
private int i;
private int j;
public A(int i, int j) {
this.i = i;
this.j = j;
}
public int getI() {
return i;
}
public int getJ() {
return j;
}
}
public static class B extends A {
private String name;
public B(int i, int j, String name) {
super(i, j);
this.name = name;
}
public String getName() {
return name;
}
@Override
public Object clone() throws CloneNotSupportedException {
if(this instanceof B && !(this instanceof C)) return new CloneNotSupportedException();
return super.clone();
}
}
public static class C extends B implements Cloneable {
public C(int i, int j, String name) {
super(i, j, name);
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public static void main(String[] args) throws CloneNotSupportedException {
B class1 = new B(20, 35, "Dog");
B class2 = (B) class1.clone();
C class3 = new C(25, 40, "Happy");
C class4 = (C) class3.clone();
System.out.println(class3 + " " + class4);
}
}