简体   繁体   中英

Using generics in abstact class that implements interface

I haven't worked with generics yet so I'm not sure how to use them in my situation. What I'm trying to achieve is to create a superclass Vector that would use generics in it and then 3 subclasses where generics type will be set as one of dimensions. Here is what I have right now:

interface sample {
    Vector sum(Vector vec);

    Vector subtraction(Vector vec);

    int product(Vector vec);

    boolean compare(Vector vec);

    String ToString();
}

abstract class Vector implements sample {
    int[] coordinates;

    public Vector(int[] coordinates) {
        this.coordinates = coordinates;
    }

    abstract Vector resVec();

    public Vector sum(Vector vec) {
        Vector result = resVec();
        if (this.coordinates.length == vec.coordinates.length) {
            for (int i = 0; i < vec.coordinates.length; i++) {
                result.coordinates[i] = this.coordinates[i] + vec.coordinates[i];
            }
        } else {
            throw new ArithmeticException("Can't sum vectors of different length");
        }
        return result;
    }

and two subclasses for example: 1)

class Vector3D extends Vector {

    public Vector3D(int n1, int n2, int n3) {
        super(new int[]{n1, n2, n3});
    }

    public Vector3D resVec() {
        Vector3D resVec = new Vector3D(0, 0, 0);
        return resVec;
    }

    public Vector3D sum(Vector vec) {
        return (Vector3D) super.sum(vec);
    }

2)

class Vector5D extends Vector {
    public Vector5D(int n1, int n2, int n3, int n4, int n5) {
        super(new int[]{n1, n2, n3, n4, n5});
    }

    public Vector5D resVec() {
        Vector5D resVec = new Vector5D(0, 0, 0, 0, 0);
        return resVec;
    }

    public Vector5D sum(Vector vec) {
        return (Vector5D) super.sum(vec);
    }

So what I want to get as a result is for example if I type in main something like this: Vector3D vec1 = new Vector3D(1,2,3); Vector5D vec2 = new Vector5D(1,2,3,4,5); and use A.sum(B); I should get a compile error because of wrong type of variable has been passed to sum method. Thanks!

That's not the responsibility of the type hierarchy; that's the responsibility of the concrete class.

The big thing here is that your sum method is accepting a type of Vector , and the implementors of that sum method should know what is and is not a valid type that they can perform against. Adding an instanceof check to your sum method should be all you realistically need.

Generics would help if you wanted to ensure type homogeneity across a collection of vectors, but I don't see it being of much value in this case when you know for a fact what each vector is capable of operating on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM