Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an object as a variable for a constructor

I have a question about using an object as the variable in a constructor. It might be simple but I just really can't think of what to do and my java book isn't really helping. Say i wanted to do this

Fraction f3 = new Fraction(1, 2);
Fraction f5 = new Fraction(f3);

my constructor for the first object is:

public Fraction(int n, int d)

{
    if (d == 0)
    {
        numerator = 0;
        denominator = 1;
        System.err.println("Error: Invalid Denominator (" + d + ")");
    }
    else if (d < 0)
    {
        int nn = Math.abs(n) * (-1);
        numerator = nn;
        denominator = Math.abs(d);
    }
    else
    {
    numerator = n;
    denominator = d;
    }

}

my constructor for the second object is this:

public Fraction(Fraction f) 

{

}

I can't think of how to define the constructor to get it to set a new object as the object given. If anyone could give me a hand or maybe some advice to put me on the path to figuring it out I would greatly appreciate it.

like image 665
lostprophet1 Avatar asked Dec 28 '25 15:12

lostprophet1


1 Answers

public Fraction(Fraction f){
  this(f.numerator, f.denominator);
}
like image 167
ziesemer Avatar answered Dec 31 '25 03:12

ziesemer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!