简体   繁体   中英

Convert sub-type to super-type

I have a abstract super class A, and a subclass B that extends this class.

public abstract class A {

}

public class B extends A {


}

I have a method that returns type A, but object 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?

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 .

This is not allowed: A a = new A();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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