Java Generic how to change parameterized subclass
I have a structure like this:
public class Record{}
public class ParsedRecord extends Record {}
public class RecordsList extends ParsedRecord {}
public abstract class Processor<T extends Record >{ private BlockingQueue<T> queue;}
public class Dispatcher extends Processor<ParsedRecord> {
List<ParsedRecord> list;
public Dispatcher() {
}
public void process(ParsedRecord record){
//blabla
}
}
I want to use the Dispatcher class with parameters ParsedRecord or any type that extends from the ParsedRecord class.
Can anyone help me understand how to properly change the definition of the Dispatcher class?
source to share
Can be as simple as changing your class definition:
public class <T extends ParsedRecord> Dispatcher extends AbstractProcessor<T> {
and then: use T
as the type for your list or for the parameter given process()
.
But the real answer is here: learn the concept. Don't try to go with trial and error.
source to share
You are declaring a class Processor
but extending AbstractProcessor
.
You probably made a naming error in the question.
So you only have a class AbstractProcessor
to give a specific answer.
In your case, if you want to bind a class type declaration to a method parameter, you must first declare the method in the parent class and specify its parameter with the declared type:
public abstract void process(T record){
You will have a parent class:
public abstract class AbstractProcessor<T extends Record >{
...
public abstract void process(T record);
...
}
And in the subclass, you get this symmetric declaration:
public class Dispatcher extends AbstractProcessor<ParsedRecord> {
...
public void process(ParsedRecord record){
//blabla
}
}
source to share