Q:

Rename variables in subclass

I have a simple tuple class.
public class Tuple<X, Y> { 
    public X first; 
    public Y second; 
    public Tuple(X x, Y y) { 
        this.first = x; 
        this.second = y; 
    }

    @Override
    public String toString() {
        return "(" + first + "," + second + ")";
    }

    @Override
    public boolean equals(Object other) {
        if (other == null) {
            return false;
        }
        if (other == this) {
            return true;
        }
        if (!(other instanceof Tuple)){
            return false;
        }
        Tuple<X,Y> other_ = (Tuple<X,Y>) other;
        return other_.first == this.first && other_.second == this.second;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((first == null) ? 0 : first.hashCode());
        result = prime * result + ((second == null) ? 0 : second.hashCode());
        return result;
    }
}

I use it in several different contexts. I have tuples of articles and their ID, their ID and their vector weight, etc. After a while, it gets messy only seeing first and second as the variable names, when they could mean stuff like name and id. Is there any way i can subclass this class multiple times to rename first and second to meaningful names, without needing to override toString(), equals(), and hashCode()?

A:

You can subclass Tuple and add extra getters with meaningful names. Also the constructor parameters are named. You can also enforce id to be not nullable, by declaring it as int in the constructor.
public class NameIdTuple extends Tuple<String, Integer> {

    public NameIdTuple(String name, int id) {
        super(name, id);
    }

    public String name() {
        return first;
    }

    public int id() {
        return second;
    }

}

Methods getFirst() and getSecond() still can be called (so you have full backwards compatibility).
I don't know which IDE you are using, but IntelliJ's auto-completion shows methods declared in the class in bold, others such as getClass(), equals(), getFirst() won't be in bold so it's unlikely that they will be used in the new code.

