Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract Generic class

Tags:

java

generics

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

like image 623
ronen Avatar asked Nov 06 '09 21:11

ronen


2 Answers

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

public class SumOfInts extends Step<Integer,Integer> {
    // etc.
like image 160
Jonathan Feinberg Avatar answered Sep 25 '22 00:09

Jonathan Feinberg


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.

like image 34
KLE Avatar answered Sep 23 '22 00:09

KLE