开发者

Abstract Generic class

开发者_如何学运维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


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

public class SumOfInts extends Step<Integer,Integer> {
    // etc.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜