0
class A { 

}
public class B extends A {

public static void main(String[] args) {
     A m = new A();
     B n = (B)m;
}
}

this code can not be complied. However, in the code below, this downcast works.

 class A { 

}
public class B extends A implements Cloneable{

@Override
public B clone() throws CloneNotSupportedException {
return (B)super.clone();
}
public static void main(String[] args) {
     B m = new B();
     B n = m.clone();
}
}

so, why this downcast works?

=============Correction============================

sorry for my fault, it should be B n = **(B)**m;, not B n = m;. I'm very sorry. I have corrected it in the above code.

andy
  • 3,951
  • 9
  • 29
  • 40

2 Answers2

1

Even in first case -; class A {

       }
    public class B extends A {

    public static void main(String[] args) {
     A m = new A();
   //  B n = m;
     B n = (B)m;
   }  
     }

It's work.

Mohsin Shaikh
  • 494
  • 1
  • 4
  • 11
0

WHAT? You cannot cast A to B no mather what you people are saying IF A extends B than B can be threated as insance of A and B but A cannot be instance of B.

Antoniossss
  • 31,590
  • 6
  • 57
  • 99