I’ve created a Vector2D class that extends Point2D.Double.
A Vector2D has two fields: magnitude and direction. The extension of Point2D.Double allows the vector to store a starting location as well.
I like the ability to do this:
Vector2D myVector = new Vector2D(50, 50); // instantiated without direction or magnitude
Point2D.Double myPoint = new Point2D.Double(myVector.getLocation());
However, I’d like to disallow this:
Point2D.Double myPoint = myVector;
And this:
Point2D.Double myPoint.setLocation(myVector);
Because both of these operations treat a myVector as if it is just a Point2D.Double.
I know that Java doesn’t allow overriding or overloading of operators, so the first undesired case seems especially difficult to eliminate. I also know that I can override .setLocation() with an empty method body (to prevent its use), but that’s not really a great solution.
Is there a way to disallow Vector2D methods or operators that exist in Point2D.Double?
I’m failing to see the issue here. If you want Vector2D to be a subclass of Point2D.Double, then you are explicitly declaring that it IS a Point2D.Double. If the client wants to use it as a Point2D.Double that is allowed, and completely legitimate.
It sounds like what you are trying to accomplish is subclassing as a code reuse system, rather than as a true is-a relationship. This is generally considered an anti-pattern.
Either accept that clients can do this (even though you dislike it), or switch to a composition object instead.