Reputation: 700
I am having some problems with my syntax. I am looking all over and could not find the correct thing (I actually do not know, what would be the phrase to search). So here is the problem. For simplicity, lets assume I have 4 classes:
class A:
public abstract class A{
}
class B:
public class B extends A{
//some methods and fields
}
class C:
public class C extends A{
//some other methods
}
class D:
public class D{
protected ? value;
}
Here I have a problem, because I do not know what to put instead of ?
in class D
, if I want to define ?
as some sub-class of A
. I know an option is just to write A
instead of ?
, but I think that this could be more specified, for example something like <T extends A>
.
Is this even possible?
-edit-
From answers below, I saw that approach would be, to use raw types. But nevertheless, can anyone confirm that a construct like this, does not exist in java? That you could create a field of generic type T
(extending some class), but the class containing this field does not have a generic parameter T
?
Upvotes: 0
Views: 107
Reputation: 22191
Use a generic class as follows:
public class D<T extends A> {
protected T value;
}
MyClass
isn't dependent of T
as you pretend in your comment above. You can instantiate an instance without precising wildcard. Therefore, T
would still be remplaced by A
at compile-time
This concept is called: Raw types
For more information: http://docs.oracle.com/javase/tutorial/java/generics/rawTypes.html
Upvotes: 1
Reputation: 33544
- Use Type Parameter
,
Eg:
public class MyClass<T extends A>{
T value;
}
Upvotes: 1
Reputation: 41240
I think you should specific to this value Type at run time .
public class D<T extends A>{
protected T value;
}
D<B> d =new D<B>();
D<A> d1 = new D<A>();
Upvotes: 1