简体   繁体   中英

Why cannot assign a subtype value to a generic type?

Could anybody explain:

class Test<T extends BaseDao>{

    void someMethod(){
        T inst = new Dao();      // required type T provided Dao
        T inst2 = new BaseDao(); // required type T provided BaseDao
    }

}

class Dao extends BaseDao{}

We have T type as a subtype of BaseDao. Why cannot assign Dao or BaseDao types to T type?

T can be an instance of Dao, but you cannot assign a new istance of Dao to the generic type T like this because T could refer to any class extending BaseDao.

If you need to have some specific instance of Dao you should do

Dao inst = new Dao()

If instead you do want a specific instance, but you don't want to know the specific class, you could pass inst1 and inst2 as parameters, or pass a string and create an instance by name, or many other possibility.

In short, T inst = new Dao(); makes no sense because it collides with the purpose of generics.

Imagine

Test<MySpecialDao> specialDao = new Test<>();

Now, for a call like specialDao.someMethod() ,

void someMethod(){
    T inst = new Dao();      // required type T, provided Dao
    T inst2 = new BaseDao(); // required type T, provided BaseDao
}

effectively becomes

void someMethod(){
    MySpecialDao inst = new Dao();      // required type MySpecialDao, provided Dao
    MySpecialDao inst2 = new BaseDao(); // required type MySpecialDao, provided BaseDao
}

and of course, both Dao and BaseDao aren't subtypes of MySpecialDao , probably supertypes.

I'd change to

void someMethod(){
    Dao inst = new Dao(); 
    BaseDao inst2 = new BaseDao();
}

hoping that this change doesn't break your intended logic.

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