简体   繁体   中英

How to assign child class instance to generic (extends parent) object?

I have a parent class defined like this:

public abstract MyParent {

    public static <MP extends MyParent> MP getInstance(Object... params) {
        return new MyChild(params);
    }
}

where MyChild extends MyParent . The problem is the compiler wont let me return the new child because " MyChild cannot be converted to MP ". If I cast before return ( return (MP) new MyChild(params); ) I get an unchecked cast warning.

What is the correct way to do this?

MP can be anything that extends MyParent, but MyChild is not going to be a subclass of every subclass of MyParent.

I think your intention here is to have getInstance return an instance of MyParent instead of having it return a generic MP.

Since you

have [three] MyChilds, and [] get a diferent Child according to the parameters

you have a fundamental challenge: how does the invoker of your method know which return type to expect, and how can the compiler know in advance that the type of the object actually being returned is compatible with the type the invoker expects? Compile-time type safety absolutely depends on the latter analysis, and without that, anything you imagine doing to avoid casts is just obfuscatory.

The specific relationship between your method parameters and result type is unclear, but if it depends on anything beyond the types of the parameters, then you're done. In that case there is no avoiding a cast or cast-equivalent somewhere. Your better options then include

  • have the method return MyParent , and accept that the invoker will need to cast the result if it depends on the specific subtype (but not otherwise).

  • create a different and differently-named method for each actual return type. This will avoid the need for the invoker to cast, but it may require provision for an exception in the event that the given parameters do not correspond to an object of the correct type for the method called.

Of course, you may also be able to modify the method so that the return type is based on the types of the parameters. For example, you might

  • include a type-token among the method paramerers. For this to serve as other than a cast equivalent, however, the method needs somehow to associate the type token with the other parameters, or to use it to genuinely select the return type, or coerce the return value to the specified type.

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