I have a data description interface:
public interface DataDescription {
int getId();
}
And two implementations:
public class DataWithId1 implements DataDescription {
// ... simple getter impl.
}
public class OtherDataWithId implements DataDescription {
// ... simple getter impl.
}
Now I have this interface:
public interface DataProcessor {
void process(DataDescription data);
}
I would like to implement the DataProcessor
with one class, something like this:
public class DataProcessorImpl implements DataProcessor {
@Override
public void process(DataDescription data) {
// Do something...
}
public void process(DataWithId1 data) {
// Do something specific with this type (e.g. directly store in table of database)
}
public void process(OtherDataWithId data) {
// Do something specific with this type (convert to format DataWithId1 and then store in DB)
}
}
And some code to call it:
public Main {
private DataProcessor dataProcessor = new DataProcessor();
public static void main(String[] args) {
DataDescription data = new DataWithId1(1);
dataProcessor.process(data);
}
}
What I would like to achieve is that the DataProcessor
caller doesn't have to worry about the data conversion (they have a DataDescription
and don't have to know about the two types). Additionally I would like to avoid instanceof
code.
The assumption I've made is that I can overload an interface method like this. I was unable to find proof for this when looking at section 15.12 of the java language specification (which doesn't mean it isn't there...).
Is my assumption about overloading correct? Can I avoid instanceof
?
No, this won't work.
There is no overloading in your code. dataProcessor
's static type is DataProcessor
, and DataProcessor
only has one process
method.
If you change dataProcessor
's static type to DataProcessorImpl
, you still won't get the desired outcome, since overloading resolution is determined at compile time. Therefore, since the compile time type of data
is DataDescription
, dataProcessor.process(data)
will still invoke public void process(DataDescription data)
and not public void process(DataWithId1 data)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With