// generic class example // A and B stand in for types to be specified // no problem inheriting from ordinary class public class MyPair extends Namey{ private A first; private B second; // can have default constructor, so we can set non-generic vars public MyPair() { super("An Empty Pair"); first = null; // this is really all we can do with generic instance vars here second = null; } // constructor public MyPair(A vala, B valb){ super("My Pair "); setFirst(vala); setSecond(valb); } // constructor public MyPair(A vala, B valb, String nval){ super(nval); setFirst(vala); setSecond(valb); } // accessor for first public A getFirst() { return first; } // mutator for first public void setFirst(A val) { first = val; } // accessor for second public B getSecond() { return second; } // mutator for second public void setSecond(B val) { second = val; // this line doesn't make sense even if second will sometimes be a Cat // when writing generic class, treat unknown types as Object // val.miaow(); } // compare for equality public boolean equals(Object other ) { if (other != null && other instanceof MyPair) { MyPair p = (MyPair)other; return this.getName().equals(p.getName()) && this.getFirst().equals(p.getFirst()) && this.getSecond().equals(p.getSecond()); } return false; } // string is the pair in parens public String toString() { return getName() + ": ("+getFirst()+", "+getSecond()+")"; } }