Question

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.

Était-ce utile?

La solution

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.

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top