using keyword this with multiple constructors in a Class

636 Views Asked by At

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

There are 3 best solutions below

3
On BEST ANSWER

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

0
On

this refers to the current object.

But

this() will call current class constructor that is default constructor.

this(val) will call class constructor with one argument...

this(val1,val2) call class constructor with two argument...

now if you call this() only but you have written you constructor in such way where you might have called other this(withArg). like below..so you can write nested way too.

public Rational(){
    this(0);
}

1) The this keyword can be used to refer current class instance variable.

public Rational(int num, int den){
     this.num = num; 
     this.den = deb; 
  }

2) this() can be used to invoked current class constructor.

   public Rational(int num, int den){
             this(num);
             this.den = deb; 
          }

3)The this keyword can be used to invoke current class method (implicitly).

public Rational(){
        this.someMethod();
    }
2
On

The term

Rational r = new Rational();

calls upon

public Rational(){
    this(0);
}

which calls upon

public Rational(int 0){
    this(0,1);
}

which calls upon

public Rational(int 0, int 1){
   num = 0; 
   den = 1; 
}

which means your final object will be Rational(0,1);