I'm experimenting with generics in Java, and thought of this example.
If I have ClassA<T>
, I can override it with a subclass that references a concrete class, such as ClassB extends ClassA<String>
, then anywhere ClassA uses T, ClassB can use a String.
Now, ignoring the previous ClassA
and ClassB
, if I have an abstract ClassA
, which has a generic method:
public <T> void doSomething(T data);
Is there any way I can have a ClassB
that overrides it with a concrete class, similar to the previous example? I've come up with something that works, which is to parameterize both the class and the method, but I'm wondering if there's another way.
class ClassA<T> {
public void doSomething(T data) {};
}
The reason I don't want to put the parameter in the class is because it's only one method that does anything with that type, and some subclasses may not even want to do anything in that method, so I shouldn't need to put a parameter in the class if it's not going to use it.
NOTE: All of the subclasses of ClassA
are anonymous classes, so that adds to the fun.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…