简体   繁体   中英

Java Subclasses that have different primitive data members, but same methods

I'm writing a Ray Tracer and I have a Vec3 class which is a typical math vector with 3 coordinates: X, Y, and Z. I've also created a Color class that holds 3 components: R, G, and B. After writing a decent amount of code, I started to notice that Color is basically a Vec3. I started to write a lot of the same methods for Color as I did for Vec3. Seeing that DRY code is the way to go, I wanted to merge the two classes so I didn't have to keep writing the same code for both classes.

As it stands, here are the classes:

class Vec3{
    public static final int X=0,Y=1,Z=2;
    double components[];
    ...
    // Constructors and Methods
}

class Color extends Vec3{
    public static final int R=0,G=1,B=2;
    int components[];
    ...
    // Constructors and Methods
}

The only difference between the two classes is that a Vec3 uses doubles for its components and a Color uses ints. Other than the type of data, all of the methods are exactly the same. My original inclination was to try and make a BaseVec3 class of generic type T and then just declare the type in the subclasses. But, of course, a generic requires a class, not a primitive.

Is there any way I can have a single method code-base but with different primitive data types?

Edit: I should probably note that I have been programming in Python and C for a while and it's been a while since I've touched Java. So, my first instinct answer to this question is NO .

I'm not 100% sure of what you're asking, but if your code is as you've shown, don't you have what you want? In your code, Color extends Vec3 . Due to this statement, a Color object can be treated as a Vec3 object; all methods from Vec3 are inherited by Color and methods which take an arg of type Vec3 will accept args of type Color.

Each primitive has its corresponding class. For example, Integer for int . Java can autobox them, ie convert them automatically.

However, I don't think using inheritance is appropriate in this case. What if you Vec3 implementation change? What if you decide to make you members private (as you should)?

EDIT - I see your comment about generics at the end. Isn't that what autoboxing is for?

Couldn't you just use a generic like this?

public abstract class GenericVector<T> {
    private final T x, y, z;

    public GenericVector(T x, T y, T z) {
        this.x=x;
        this.y=y;
        this.z=z;
    }

    public T getX() { return x; }
    public T getY() { return y; }
    public T getZ() { return z; }
}

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