I am rather inexperience in Java, and I'm having a problem in forming a subclass of a class I have created. The class I have made, called Vector2D
, contains methods, such as add(Vector2D addend)
, that takes a Vector2D
object as an argument, and returns a Vector2D
object. This method in particular is designed to add two vectors, and return the sum.
Then, I started coding a subclass, called Position2D
, which I intend to have all of the functionality of the Vector2D
class, except have additional functions, and have any usage of Vector2D
inside the preexisting classes, be it as an argument, return type, etc., replaced with Position2D
, so that the add(Position2D addend)
function adds two Position2D
vectors together, and returns the sum as a Position2D
.
The issue arises that, when Position2D
inherits from Vector2D
, such functions continue to work in terms of Vector2D
objects, spitting out an error as soon as a Position2D
object is passed through it.
The relevant code for the Vector2D
class is as follows:
public class Vector2D{
//Field Variables
private double x; //The vector's x-coordinate
private double y; //The vector's y-coordinate
//Constructors
public Vector2D(){
//Constructs empty vector.
setX(0);
setY(0);
}
//Methods
public void setX(double newX){
//This method is not problematic when inherited for the subclass.
x = newX;
}
public void setY(double newY){
//This method is not problematic too.
y = newY;
}
public Vector2D add(Vector2D addend){
//Adds two vectors and returns the sum.
//This method, however, does pose a problem.
Vector2D sum = new Vector2D();
sum.x = x + addend.x;
sum.y = y + addend.y;
return sum;
}
}
The only work-around I can currently think of as to what the code in add(Position2D addend)
in Position2D
could be is:
public Position2D add(Position2D addend){
//Adds two position vectors and returns the sum.
Position2D sum = new Position2D();
sum.x = x + addend.x;
sum.y = y + addend.y;
return sum;
}
i.e., repeat the method from Vector2D
, and manually modify it. This, of course, is not efficient and wastes time, especially so whenever the same has to be done for similar methods, and more so whenever I intend to make more subclass, e.g. Velocity2D
. Therefore, I am looking for a much cleaner and efficient means of doing this.
add
isn't defined for points. If you have position vectors as you claim you do, then you already have those in the form ofVector2D
; it makes no sense to create a separate type. If your intention is to distinguish between vectors with different units then you should probably be using generics so you can't addVector2D<Kilometers>
withVector2D<KilometersPerHour>
.