Just started learning java recently, and in my textbook I came across this
which was very confusing at first but now its starting to make sense. Now, in my book we
started basic applications of constructors and as a side note on the page it said this
, can also be used to call other constructors. I was a bit confused, then
look at other questions on SO regarding this
. I think I get it to an extent now, but WHY would I ever want to do this? Consider the following which I just made up.
private double balance;
private double interest;
public Account(double initialBalance){
balance = initialBalance;
}
public Account(double balance, double interest){
this(0);
balance = initialBalance;
this.interest = interest;
}
Here this(0);
, to my understanding looks for another constructor with one parameter, finds Account(double initialBalance)
, and sets initialBalance
to zero.
Great. Erm, but why wouldn't I just do that directly? Just set balance equal to zero! I am sure it is very useful but I can't think of any examples.
Thanks!