My home work so far now. Now I must implement a generic class Coordinate as Pair of two numeric (subtype of Number) values. The getDistanceFromOrigin method returns the distance from the coordinate to the origin.
I get stuck with the Coordinate class, what did I do wrong?
Stephan van Hulst wrote:The ^ operator isn't defined for Number. You must convert your numbers to double first.
Double doesn't work here; it would have to be an integral type (byte, short, char, int, long). Which is just a symptom of the real problem: in Java, the ^ operator doesn't do exponentiation; it's an exclusive or -- either bitwise or boolean, depending on the arguments. To square a number x, we either use Math.sqrt(x), or just write x*x.
Your constructor is incorrect. It doesn't use the values t and s.
Why are you creating your own exception class? Throw a NullPointerException if there are problems with nulls.
Don't use squares, nor square roots. Not if you can use this method. That gives me a problem: that method takes (double, double) as its parameters. You cannot simply use unboxing to get the value for the method call, but you can use a method of the Number class.
Why are you making your coordinate class extend Pair (even if you aren't making it extend Pair)? Have you been told to create subtypes of Pair? Maybe you would do better to find out about, “Favour composition over inheritance,” and give that class a Pair as a field.
Don't write the generic types twice (line 22,‑23). Use type inference and miss out the second pair of types: write <> on its own.
Now Coordinate extends Pair.
Constructor now use values t and s.
Created an own exception class, because this is asked in assignment. Indeed is NullPointerException also possible.
The assignment asks to implement Coordinate as Pair, so guess inheritance.
Indeed, my fault about generic types twice.
There is nothing written in the assignment about two generic types.
Changed getDistanceFromOrigin(), but doesn't work. Method hypot() gave problems indeed. What did I do wrong?
Thanks so far.
Alexander Visser wrote:Now I must implement a generic class Coordinate as Pair of two numeric (subtype of Number) values.
This is a bit ambiguous. It doesn't say whether the two numeric values must be of the same subtype of Number, or whether they can be of different subtypes. You said "subtype" (singular) which sort of suggests only one subtype, but it doesn't definitively say that. So it might be that "public class Pair<T, T>" is what you were supposed to do.