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