Reputation: 12211
Ok, so I've been playing around with this for a little while and I'm starting to believe that generics don't work the same way in Java or I'm missing something. I come from a c# background.
In C#, I might implement a generic interface like so:
public interface ICalculatorOperation<TInput, TOuput>
{
TOuput RunCalculation(TInput input);
}
public class MyCalculator : ICalculatorOperation<MyCalcInput, MyCalcOutput>
{
public MyCalcOutput RunCalculation(MyCalcInput input)
{
// implemented code ...
}
}
When I tried to take this same approach in Java, this was my first instinct:
public interface Calculates<TInput, TOutput>{
<TInput, TOutput> TOutput RunCalculation(TInput input);
}
public class MyCalculator implements Calculates<MyCalcInput, MyCalcOutput>{
@override
public MyCalcOuput RunCalculation(MyCalcInput input){ // compile error, doesn't implement interface
// implemented code ...
}
}
But as you can see, this won't compile. Even though I set the parameters to the concrete types that I'll being using for this implementation, the compiler still expects to see the actual signature of the interface (sorry, this is weird to me lol).
So I tried this:
public class MyCalculator implements Calculates<MyCalcInput, MyCalcOutput>{
@override
public TOuput RunCalculation(TInput input){
MyCalcOutput result = new MyCalcOutput();
// set the results to this object
return result; // compile error, return type must be TOutput
}
}
Now the signature of the method matches that of the interface and the compiler is happy, however now my return statement doesn't work.
It's obvious that there are some differences that I haven't been able to pick up from the docs that I've found on the net or the articles here on SO. I'm hoping someone can shed some light on this?
Upvotes: 1
Views: 99
Reputation: 27094
Try this interface instead:
public interface Calculates<TInput, TOutput> {
TOutput RunCalculation(TInput input);
}
(remove the "method local" generic types you have declared, which probably confuses you and/or the compiler).
Then, your initial implementation should work.
PS: It's also convention to use single letter generic types in Java, so <I, O>
would be more familiar to Java developers.
Upvotes: 3