Meberem
Meberem

Reputation: 947

Java Generics Inheritance

I have 2 different types of data managers, one inherits the other and both rely on 1 base data class and looks like this:

public abstract class BaseDataType {
    ...
}

public class BaseManager<DataType extends BaseDataType> implements ListModel{
    ...
    public final DataType get(index i){
        return dataList.get(i);
    }
    ...
}

public class BaseSQLManager<DataType extends BaseDataType, Adapter extends SQLAdapter>
    extends BaseManager<DataType>{
    ...
}

My understanding that using BaseSQLManager m =new BaseSQLManager<Property, PropertSQLAdapter>(); would allow me to use Property p = m.get(i); however I am informed that the get method returns BaseDataType.

I'm sure I'm missing something small here and I can't figure it out. An explanation of why this doesn't work would really help. Thanks

Upvotes: 3

Views: 1361

Answers (1)

meriton
meriton

Reputation: 70564

BaseSQLManager m =new BaseSQLManager<Property, PropertSQLAdapter>();

Yes, you are missing the type parameter in the variable declaration, i.e. the type of m does not constrain the type parameter, which is why get() is only known to return something that extends BaseDataType. It should be:

BaseSQLManager<Property, PropertSQLAdapter> m 
    = new BaseSQLManager<Property, PropertSQLAdapter>();

Upvotes: 3

Related Questions