What is the purpose of this code?
public Fraction(Fraction other) {
num = other.num;
denom = other.denom;
}
If you have a constructor like this:
public Fraction(int n, int d) {
num = n;
denom = d;
}
Why do you have to initialize other.num
to num
and other.denom
to denom
. What is with the syntax of the copy constructor? What is the purpose?
If you were to simply type
public Fraction(Fraction other) {
}
Java isn't simply going to guess that you want to copy the values of other
into the new object. Java does not automatically initialize your variables for you like that. For it to be a copy constructor, you still have to manually type out the code that copies the fields from other
to the object you are creating. Like this:
public Fraction(Fraction other) {
num = other.num;
denom = other.denom;
}
The constructor creates a new Fraction
but it is the code you type inside it that manually performs the "copying" that makes it a "copy constructor" and allows you to do
Fraction a = Fraction(4, 20);
Fraction b = new Fraction(a);
// b has the same values as a but is a different object
Of course, if you already have another constructor, a shorter way to make a copy constructor is
public Fraction(int n, int d) {
num = n;
denom = d;
}
public Fraction(Fraction other) {
this(other.num, other.denom);
}