user242083
user242083

Reputation: 13

Java - derived generics class for math functions

This was a hard problem to try and search for as I've seen no other specific issues like this, so I apologize if there turns out to be a duplicate thread I haven't found. This is a programming problem that is not related to homework in a class, that I am having issues implementing exactly according to spec.

If I want to create a

Function<T>

generic abstract class, whose only abstract method is

Apply<T>(T input1, input2)

and then extend into other derived function classes like an AddTwoNumbers class, to which Apply would return the sum of those input1 and input2 of type T (in practice this should be Integer or Double), how can I implement this?

I run into a problem when I first have

public abstract class Function<T1 extends Number> {
    public abstract T1 apply(T1 input1, T1 input2);
}
public class AddTwoNumbers<T1 extends Number> extends Function<T1> {
    public T1 apply(T1 input1, T1 input2) {
        return input1.intValue() + input2.intValue(); //Error, needs to return type T1, not int or even Integer()
    }
}

It is required that Function be generic that allows types, but inpractice it can be expected that AddTwoNumbers will be using Integers exclusively for the sake of this problem. Is there a way I can write the apply() method in AddTwoNumbers, such that

  1. AddTwoNumbers implements the abstract methods inherited from Function exactly
  2. Somehow add the two T1 values and return a T1 value properly?

The fact that I can't safely cast a T1 to an Integer, and also retain the overriding of Apply is the troublesome part.

This is generalization of the issue I was looking into.

Upvotes: 1

Views: 215

Answers (2)

torquestomp
torquestomp

Reputation: 3344

What you're asking for unfortunately isn't possible within the Java specification. There is no abstraction layer which accounts for both primitive ints and primitive doubles, or in fact any combination of primitives, so you are forced to create two classes for this.

There are ways of doing this, however, which are much better than writing an AddTwoIntegers.java file AND an AddTwoDoubles.java file.

Option 1: Create an AdditionFunctions class, and give it two static members: INTS and DOUBLES. You can do this using anonymous classes easily.

Option 2: Use a template, if you can incorporate the generation step into your build process. Trove does this to great effect

Upvotes: 0

Judge Mental
Judge Mental

Reputation: 5239

public class AddTwoIntegers extends Function< Integer > {
...
}

Upvotes: 1

Related Questions