Search code examples
javaclassinheritancevectorabstract-class

Java Creating a vector with multiple ends


I want to create two types of vectors (as classes):

  • The first type is a regular vector with two components (a start and an ending point).
  • The second type is also a vector but instead of having one it has two ending points you can switch between.

My idea was to create an abstract superclass (e.g. AbstractVector) in which I define the common functions of the vectors:

abstract class AbstractVector {
    //Methods, e.g. length(), getter...
}

Then my two subclasses Vector and (e.g. ) TriVector extend the above class. The problem I'm facing is handling of the two ending points in the TriVector class. I absolutely have no idea on how to do it or how to set up the abstract class correctly so I can have a normal vector and a vector with two endings between which I can switch (e.g. the TriVector class has a method switch() which switches between the two ending points).

I hope somebody can help me or propose a better solution.


Solution

  • A very rough sketch for a solution, only detailing the getStart() and getEnd() methods:

    abstract class AbstractVector {
        protected Point startPoint;
        public Point getStart() {
            return startPoint;
        }
        public abstract Point getEnd();
        //Methods, e.g. length(), getter...
    }
    
    class Vector extends AbstractVector {
        protected Point endPoint;
        public Point getEnd() {
            return endPoint;
        }
    }
    
    class TriVector extends AbstractVector {
        protected Point[] endPoints = new Point[2];
        protected int activeEndPoint = 0;
    
        public Point getEnd() {
            return endPoints[activeEndPoint];
        }
    
        public void switchEnds() {
            activeEndPoint = 1 - activeEndPoint;
        }
    }