I am experimenting with generics in Java and am thinking of this example.
If I have ClassA<T>, I can override it with a subclass that refers to a particular class, for example ClassB extends ClassA<String>, then in any case ClassA uses T, ClassB can use String.
Now, ignoring the previous ones ClassAand ClassBif I have an abstract ClassAthat has a common method:
public <T> void doSomething(T data);
Is there a way that I can have ClassBthat overrides it with a concrete class similar to the previous example? I came up with something that works, that I need to parameterize both the class and the method, but I wonder if there is 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 is the only method that does something with this type, and some subclasses may not even want to do anything in this method, so I don’t need to put parameter to the class if it is not going to use it.
NOTE . All subclasses ClassAare anonymous classes, which adds to the fun.
source
share