java - Instance variables default value -


my book says 1 of crucial differences between local variables , instance variables must initialize local variables , instance variables default value of 0 if don't initialize them. shortly before did example introducing constructors, , public void , public double , return do.

consider following example did in book. here balance instance variable.we have 2 constructors below it. if instance variable gets default value of zero, why need first constructor

public account(){         balance = 0;         } 

saying if call account acc = new account(); balance = 0. doesn't 0 automatically? @ least thats understanding book

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

you don't need first constructor never call anywhere.

assuming was called somewhere, wouldn't need line balance = 0 in it, people still add it, make explicitly visible , clear it's intentional (sometimes automatic things used unintentionally).

if removed constructor entirely , tried instantiate account using new account() (without parameters), wouldn't work don't have zero-argument constructor anymore (another magic thing: java generate 1 if , if don't have other constructors).


Comments

Popular posts from this blog

gridview - Yii2 DataPorivider $totalSum for a column -

java - Suppress Jboss version details from HTTP error response -

Sass watch command compiles .scss files before full sftp upload -