I wanted to implement a class which will be used to represent points in space. To do this, it makes use of three attributes (coordinates x, y, z) of which two of these coordinates exist in another class and a series of methods that exist in a class that represents points on the plane. This class has a number of methods.
Method coordinates()
: Returns an array with the coordinates of the points
Method equals()
: Evaluates if the coordinates are equal or not
Method toString()
: Represents the coordinates
Problems I have in the second class: When inheriting the method .toString()
and adding +
the coordinate z
to it, it is not represented in the form (x, y, z)
but as(x, y)z
Finally, when inheriting the method coordinates()
it is only represented in the form [x, y]
it does not let me add the coordinatez
Class points in the plane
import java.util.Arrays;
import java.util.stream.Collectors;
public class Point2D {
protected double x, y;
public Point2D(double x, double y) {
this.x = x;
this.y = y;
}
public double[] coordinates() {
double[] result = {this.x, this.y};
return result;
}
@Override
public boolean equals(Object other) {
Point2D iterable = (Point2D)other;
if (other instanceof Point2D) {
return Arrays.equals(this.coordinates(), iterable.coordinates());
} else {
return false;
}
}
@Override
public String toString() {
return Arrays.stream(this.coordinates()).mapToObj(Double::toString)
.collect(Collectors.joining(", ", "(", ")"));
}
Class points in space inherited from class points in the plane
public class Point3D extends Point2D {
protected double z;
public Point3D(double x, double y, double z) {
super(x, y);
this.z = z;
}
@Override
public boolean equals(Object other) {
Point3D cast = (Point3D) other;
if (other instanceof Point3D) {
return this.coordinates() == cast.coordinates();
} else {
return false;
}
}
@Override
public double[] coordinates() {
return super.coordinates(); // Problema: Expected output = [x, y, z]
} // Output recibido: [x, y]
@Override
public String toString() {
return super.toString() + this.z; // Problema: Expected output = (x, y, z)
} // Output recibido = (x, y)z
Your Point3D class should look like this:
The toString method when receiving the inheritance you must rewrite it completely so that it works as you want and also the rest of the methods that do not work as you want. For the toString method you would have something like this: