Search code examples
javaclassgenericscomparable

Creating a Generic for a Class


Assuming you have a class named Rational where each object contains two ints representing the numerator and the denominator, write the class definition line if you wanted to indicate that it would implement the generic interface Comparable and write the body of the required method with the signature:

public int compareTo(Object other);

so that it will only return -1 or 0 or +1 based on the relative order of the two objects based on the numerators and denominators.

I don't understand how to create a generic for Rational1, that takes the two integers (numer, denom). Any help with this, will be greatly appreciated. This is my Rational1 class so far:

public class Rational1 implements Comparable<Rational1> {
    private int numer;
    private int denom;

    public Rational1(int numer,int denom){
        this.numer = numer;
        this.denom = denom;
    }

    public Rational1(Rational1 po){
        po = new Rational1(numer, denom);

    }

    public int compareTo(Object other){
        other = new Rational1(numer, denom);
        if(numer>denom){
            return 1;
        }
        else if(numer<denom){
            return -1;
        }

        else{
        return 0;
        }
    }

}

And this is my interface:

public interface Comparable<Rational1> {
    public int compareTo(Object other);

}

And Lastly, my main which gives me an error on the last line when I call the generic:

public class Rational {

    public static void main(String[] args){
        Rational1 rational = new Rational1(4,3);
        Comparable<Rational1> ration = new Comparable<Rational1>();
    }
}

Solution

  • First things first, even if it is not direclty related with the question your constructor

    public Rational1(Rational1 po) {
        po = new Rational1(numer, denom);
    }
    

    is a complete nonsense. It should be

    public Rational1(Rational1 po) {
         this(po.numer, po.denom);
    }
    

    Your main method is also wrong, you have to provide a concrete class not an interface (an interface can never be instantiated) :

    public static void main(String[] args){
        Rational1 rational = new Rational1(4,3);
        Comparable<Rational1> ration = new Rational1();
    }
    

    Finally, your implementation of the comparison is wrong because :

    • it's mathematically wrong
    • the signature of compareTo is not correct. It should be int compareTo(Rational1 that).
    • you are constructing a new instance instead of considering your parameter. It should be

      @Override
      public int compareTo(Rational1 that) {
          return Integer.compare(numer*that.denom, that.numer*denom);
      }
      

    Always use @Override when implementing an abstract class/interface to make sure you are indeed overriding the abstract members.