繁体   English   中英

向下转换如何工作:(B)super.clone()?

[英]how can this downcast works:(B)super.clone()?

class A { 

}
public class B extends A {

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

无法遵守此代码。 但是,在下面的代码中,此向下转换有效。

 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();
}
}

那么,为什么这种垂头丧气的作品呢?

=============更正============================

抱歉,我应该是B n = **(B)**m; ,不是B n = m; 我非常抱歉。 我已在上面的代码中对其进行了更正。

即使在第一种情况下- A类{

       }
    public class B extends A {

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

是工作。

什么? 如果将A扩展到B超过B可能会威胁到A和B的关系,那么您将无法将A强制转换为B。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM