[英]Convert sub-type to super-type
I have a abstract super class A, and a subclass B that extends this class. 我有一个抽象的超类A和一个扩展该类的子类B。
public abstract class A {
}
public class B extends A {
}
I have a method that returns type A, but object B 我有一个返回类型A但对象B的方法
public A fetchType() {
A a = new B();
return a;
}
When I call the fetchType method, I want to actually get object A. In this case, I might have to cast B to A so I get A. Can someone please advise how do I do that? 当我调用fetchType方法时,实际上要获取对象A。在这种情况下,我可能必须将B强制转换为A,这样我才能得到A。有人可以建议我该怎么做吗?
You cannot create an object if the type is abstract. 如果类型是抽象的,则不能创建对象。
Here class A
is abstract class, which means you will NEVER be able to create object A
. 这里的类A
是抽象类,这意味着您将永远无法创建对象A
This is not allowed: A a = new A();
这是不允许的: A a = new A();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.