Question

I have two class.

class Vector{
      ........
      Vector(int x, int y, int z){...........}
      public Vector sum(Vector vc){
            Vector result;
            ...........//all working and store to Vector result.
            return result;
      }
      public Vector subtract(Vector vc){................//codes}
}
class Velocity extends Vector{
      Velocity(int x, int y, int z){......}
      ................
}
class Test{
      public static void main(String args){
          Velocity v1=new Velocity(14,14,14);
          Velocity v2=new Velocity(14,14,14);
          Vector result=v1.sum(v2);     //here I want to get this result as Velocity 
                                        //I don't know how to get it....
      }
}

In similar manner I have Acceleration, Force, Momentum, Displacement class which extends Vector class....And all have same problem......besides this

Was it helpful?

Solution

Vector.java:

public interface Vector<T extends Vector> {

    public int getX();
    public int getY();
    public int getZ();

    public T sum(T other);
}

BaseVector.java:

public abstract class BaseVector<T extends Vector> implements Vector<T> {


    private final int x;
    private final int y;
    private final int z;


    public BaseVector(int x, int y, int z) {

        this.x = x;
        this.y = y;
        this.z = z;
    }


    protected abstract T createNew(int x, int y, int z);


    @Override
    public T sum(T other) {

        return createNew(x + other.getX(), y + other.getY(), other.getZ());
    }


    @Override
    public int getX() {

        return x;
    }


    @Override
    public int getY() {

        return y;
    }


    @Override
    public int getZ() {

        return z;
    }


    @Override
    public String toString() {

        return "BaseVector [x=" + x + ", y=" + y + ", z=" + z + "]";
    }

}

Velocity.java:

public class Velocity extends BaseVector<Velocity> {


    public Velocity(int x, int y, int z) {

        super(x, y, z);
    }


    @Override
    protected Velocity createNew(int x, int y, int z) {

        return new Velocity(x, y, z);
    }

}

Test.java:

    public static void main(String[] args) {

        Velocity v1 = new Velocity(14, 14, 14);
        Velocity v2 = new Velocity(14, 14, 14);
        Velocity result = v1.sum(v2);
        System.out.println(result);
    }

}

OTHER TIPS

Vector result = ((Velocity)v1).sum(v2);

=========================================================

This will not help, because you defined sum in Vector, returning Vector. To make result a Velocity you would need a sum method returning type Velocity, rather than the one in Vector that returns a Vector.

A better alternative might be to provide a Velocity constructor that takes a Vector

Velocity result = new Velocity(v1.sum(v2));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top