cresjoy cresjoy - 4 months ago 12
Java Question

Instance variables default value

My book says that one of the crucial differences between local variables and instance variables are that we must initialize local variables
and instance variables get a default value of

0
if you don't initialize them. Shortly before this I did an example introducing constructors, and what
public void
and
public double
and
return
do.

Consider the following example which I just did in my book. Here balance is an instance
variable
.We have two constructors below it. If an instance variable gets a default value of zero, why do I need the first constructor

public Account(){
balance = 0;
}


saying that if I call something like
Account acc = new Account();
balance = 0
. Doesn't it get to zero automatically? At least thats my understanding from my book

Heres the full code i was working on

public class Account {
private double balance;
public Account(){
balance = 0;
}
public Account(double initialBalance){

balance = initialBalance;
}
public void deposit(double amount){
balance = balance+amount;
}

public void withdraw(double amount){
balance = balance-amount;
}

public double getBalance(){
return balance;
}
}



public class Test {
public static void main(String [] args){
Account acc = new Account(500);
acc.deposit(500);
System.out.println(acc.getBalance());
}
}

Answer

You don't need the first constructor as you never call it anywhere.

Assuming it was called somewhere, you wouldn't need the line balance = 0 in it, but some people would still add it, just to make it explicitly visible and clear that it's intentional (sometimes automatic things are used unintentionally).

If you removed the constructor entirely and tried to instantiate an Account using just new Account() (without any parameters), then that wouldn't work as you don't have a zero-argument constructor anymore (another magic thing: Java will generate one for you if and only if you don't have any other constructors).