문제

Is it possible to inherit generic type and to force in the child class the type received?

Something like:

class A<GenericType>{}
class B extends A<GenericType>{}

Or:

class B <PreciseType> extends A <GenericType>{}

But where do I define the GenericType used in B?

도움이 되었습니까?

해결책

Given

class A<T> {}

It depends on what you try to do, but both options are possible:

class B extends A<SomeType> {};
B bar = new B();
A<SomeType> foo = bar; //this is ok

and

class B<T> extends A<T>{}; //you could use a name different than T here if you want
B<SomeType> bar = new B<SomeType>();
A<SomeType> foo = bar; //this is ok too

But keep in mind that in the first case SomeType is an actual class (like String) and in the second case T is a generic type argument that needs to be instantiated when you declare/create objects of type B.

As a piece of advice: using generics in collections is easy and straightforward, but if you want to create your own generic classes you really need to understand them properly. There are a few important gotchas about their variance properties, so read the tutorial carefully and many times to master them.

다른 팁

Assuming A is declared as class A<T> {} and you want be to be specialised on String only for example, you can declare it as class B extends A<String>.

Example:

public class A<T> {
    public T get() {
        return someT;
    }
}

public class B extends A<String> {
    public String get() {
        return "abcd";
    }
}
class B extends A<GenericType>{}

This is possible. Your B class will be a new class that extends generic A class with specific class as parameter and B will not be a generic class.

class B <PreciseType> extends A <GenericType>{}

In this case you create a generic class B which has generic parameter PreciseType. This class B extends a specific version of A, but A's parameter doesn't depend on PreciseType.

If you want to create a generic class that has a parameter which is used in specification of parent class you can use the following:

class B <PreciseType> extends A <PreciseType>{}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top