0
public class Example implements Cloneable{
     int x;
     Example(int a){
         this.x=a;
     }
     public String toString(){
         return ""+x;
     }
     public Object clone() throws Exception{
         return super.clone();
     }
}
public class Test{
     public static void main(String[] args) throws Exception{
         Example obj=new Example(0);
         Example obj2=(Example)obj.clone();
         obj2.x=1;
         System.out.println(obj);
         System.out.println(obj2);
     }
}

This program generates compile time error because it is not possible to increase the scope of the exception in the overriding methods.

Why is this so?

  • This is due to polymorphism. `clone()` only declares `CloneNotSupportedException`, i.e. the caller must only catch that exception. What should the compiler now do when a subclass is allowed to throw an `IOException`? It's the same logic for return types. E.g. `public String toString() {}` can't be overridden as `public Object toString() {}`, because the caller expects the return value to be a `String` and not some `Object` – Lino Feb 23 '22 at 11:13

0 Answers0