views:

116

answers:

2

Hi, I have the following class :

public abstract class Step {
    public abstract <S,T> S makeAStep(S currentResult, T element);
}

and I'm trying to Implement it so it will take two int's and return the sum of them , something like this :

public class sumOfInts extends Step {
    public <Integer,Integer> Integer makeAStep(Integer currentResult, Integer element){
        return currentResult + element;
    }
}

but I get the following error :

The type sumOfInts must implement the inherited abstract method Step.makeAStep(S, T)

please help me (I need it for my programming languages course homework)

I asking very kindly to write me a code that does what I want to accomplish which wont have any errors or warnings thanks in front

+5  A: 
public abstract class Step<S,T> {
    public abstract S makeAStep(S currentResult, T element);
} 

public class SumOfInts extends Step<Integer,Integer> {
    // etc.
Jonathan Feinberg
+1 - Yup, exactly right.
Topher Fangio
So THAT's how you do that! I'm pretty good with Java but never learned that aspect of generics. Good job.
Carl Smotricz
Also, the Step class itself would have to have the generics registered at the class level for this suggestion to work, not at the method level
uosɐſ
@Jason +1 I agree! I think your comment corresponds to the answer I just wrote.
KLE
A: 

I agree with Jonathan's answer.


There is also another possibility, given below, that keeps the type parameters on the method itself.

It's only theory in this case, because the class and method names suggest that this has no meaning for this example.
So I change the names for my example:

    public abstract class Step {
      public abstract <S,T> String makeAStep(S first, T second);
    }

    public class ConcatTwo extends Step {
      public <S, T> String makeAStep(S first, T second){
        return String.valueOf(first) + String.valueOf(second);
      }
    }

Note : This works because the operation uses String.valueOf(Object), that works for any type (all subclass Object). For another operation, we would have to restrict S and T, using something like
S extend Integer for example.

KLE
thanks to you all , it's working (after a long long time of me trying to make it work (did I say long time ? I meant long long long ... time) :-) take care.
ronen