javathisinstance-variablesmultiple-constructors

using keyword this with multiple constructors in a Class


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; 
}

Solution

  • From within a constructor, you can also use the this keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation. Source

    If you do

    new Rational()
    

    the empty constructor will be called. This constructor will then call the constructor with one argument, i.e.

    new Rational(0)
    

    which again will call

    new Rational(0,1)
    

    That last constructor will then set the instance variables.


    For further information look at this tutorial.

    Also interesting: Java Language Specification