Search code examples
javaclasscopy-constructorrational-numbers

Clone Method Java


I'm trying to create a clone method that will take an already created Rational and make a copy so that in my main I can do something like this:

Rational r3 = new Rational(r1);

So far I created a method in my Rational class that will take in a rational as a parameter; however I am not sure how to make the new instance look just like the parameter.

public Rational copy(Rational aRational) {
int newNum = aRational.n;
 int newDenom = aRational.d;
 return (new Rational(newNum, newDenom));

}

Any help or insight is greatly appreciated!!


Solution

  • in my main I [want to] do something like this: Rational r3 = new Rational(r1);

    This is not cloning, this is making a constructor that takes a Rational as a parameter. You can do it like this:

    public Rational(Rational other) {
        n = other.n;
        d = other.d;
    }
    

    This would let you use the code to construct new instances of Rational from existing instances.

    Note: It appears that both n and d in your class are exposed to users of your class as public variables. This is not ideal, because you have no control over the modifications that the users of your class may do to its instance variables. A better approach is to make them private, and add getters and setters to your class. This approach would let you detect attempts to set denominator to zero, which may be desirable.