Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 981
Meberem Avatar asked Nov 29 '25 01:11

Meberem


1 Answers

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>();
like image 155
meriton Avatar answered Nov 30 '25 15:11

meriton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!