JAVA: generic type class inheritance and generic type inheritance

177 views Asked by At

let me state my situation first:

I've, in a 3rd party SDK, a base class with generic type:

public abstract class BaseClass<T extends BaseDataType> {
    public abstract class BaseDataType {xxx}
    public abstract int getCount();
    public abstract someMethod(T t);
}

in my business environment, it extends BaseClass as follows:

public abstract class MyGeneralBaseClas<`how to write this???`> extends BaseClass {
    @Override public int getCount() {return some_list.size()};
    @Override public abstract someMethod(`how to write this???`);
}

in the real business, I write my class:

public class MyClass extends MyGeneralBaseClass<MyDataType> {
    @Override public someMethod(MyDataType type) {xxx}
}

public class MyDataType extends BaseClass.BaseDataType {
    xxx
}

but the code failed to compile. sorry I'm travelling and I don't have my IDE and development tools, so I cannot paste the error. but I think if you write this down in an IDE such IntelliJ Idea, it would give the error I'm encountering.

so how to write this case: inheritance of generic type, and inheritance of the class using the generic type.

what i want is, in MyClass uses the concrete class MyDataType instead of the abstract BaseDataType.

2

There are 2 answers

3
Eran On BEST ANSWER

It seems MyGeneralBaseClas should have a generic type parameter with the same type bound as BaseClass:

public abstract class MyGeneralBaseClas<T extends BaseDataType> extends BaseClass<T> {
    @Override public int getCount() {return some_list.size()};
    @Override public abstract someMethod(T t);
}
1
Darshan Mehta On

You can do it in two ways:

  1. By using BaseDataType class as is, e.g.:

    abstract class MyGeneralBaseClas<T extends BaseDataType> extends BaseClass<T> {
        @Override public void someMethod(T t){}
    }
    
  2. By extending BaseDataType class, e.g.:

    class DerivedDataType extends BaseDataType{
        //Some code
    }
    
    abstract class MyAnotherBAseClass<DerivedDataType> extends BaseClass{
        @Override
        public void someMethod(com.gamesys.application.BaseDataType t) {}
    }