Java Generic of Another generic

若如初见. 提交于 2019-12-04 05:20:57

In Java, every generic type must be specified. You can go without specifying any type, but you can't go without specifying just one.

Also, every generic type must be specified in the declaration. If you want to have class GenericDAO<T extends Identifable<U>>, you must add the generic type declaration for U to your class declaration like this (since U is actually a generic type here):

public abstract class GenericDAO<T extends Identifable<U>, U> 

The following is partially off-topic, but you might find it useful.

I've noticed that in your definition of GenericDAO two generic types are not tied to each other. This might not be what you want.

What you have here is a particular case in which the two generics are matching (the Long type in the Cat and CatDAO definitions). Consider having these declarations:

public class Dog implements Identifable<Long>
public class DogDAO extends GenericDao<Dog, String>

This would force you to write the getById method in DogDAO method:

Dog getById(String id);

Your getId method in the Dog returns a Long so your getById method int DogDAO would have to compare Strings to Longs. This is valid thing to do, but it's a bit counter-intuitive. Having a getById method for DogDAO that takes a Long parameter makes more sense, since the Dogs IDs are actually Longs.

If you want to tie the two types together, you can define the GenericDAO class as:

public abstract class GenericDAO<T extends Identifable<S>, S>

You still have to specify the second parameter, but at least the compiler can help you make sure that the types are matching.

Try this:

public abstract class GenericDAO<S extends Serializable, T extends Identifable<S>> {
    abstract T getByID(S id);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!