1

Below is my sample code:

class One implements Cloneable {
    @Override
    public One clone() throws CloneNotSupportedException {
        One obj = (One) super.clone();
        return obj;
    }
}

public class Two extends One {
    @Override
    public Two clone() throws CloneNotSupportedException {
        Two obj1 = (Two) super.clone(); // Line 12
        return obj1;
    }

    public static void main(String[] args) {
        boolean num = true;
        try {
            if ((new Two().clone()) instanceof One) {
                num = false;
            }
        } catch (CloneNotSupportedException e) {
            System.out.println(e);
        }
        System.out.println(num);
    }
}

It prints false.

Can someone explain what is happening in Line 12? Why this downcast does not throw exception?

byxor
  • 5,930
  • 4
  • 27
  • 44

1 Answers1

0

Because of line 4. It call Object.clone(). That method do MAGIC. It create new instance with the same runtime type as existing instnce.

talex
  • 17,973
  • 3
  • 29
  • 66