I don't understand what happens when you create a Rational object with the constructor Rational(). My book says it will create a Rational object whose value is 0 but internally stored as 0/1. How does this(0) get stored as 0/1? Isn't the default value of the instance variables for both num and den 0?
public class Rational{
public Rational(){
this(0);
}
public Rational(int n){
this(n,1);
}
public Rational(int x, int y){
num = x;
den = y;
}
private int num;
private int den;
}
If you do
the empty constructor will be called. This constructor will then call the constructor with one argument, i.e.
which again will call
That last constructor will then set the instance variables.
For further information look at this tutorial.
Also interesting: Java Language Specification