20 likes | 198 Views
Variable Types & Scope(Lifetime of Variable). public void deposit ( double amt ) { double newBal = myBalance + amt ; myBalance = newBal ; }. Consider from the BankAcct class:. 3 Variable Types Exist: Instance Fields ( myBalance ) -> belong to an object.
E N D
Variable Types & Scope(Lifetime of Variable) public void deposit ( double amt) { double newBal = myBalance + amt; myBalance = newBal; } • Consider from the BankAcct class: • 3 Variable Types Exist: • Instance Fields (myBalance) -> belong to an object. • Exists throughout the lifetime of the object. • Initialized through constructors. • Local Variables (newBal) -> belong to a method • Dies when method is done. • Must be declared in method body and initialized. • Parameter Variables (amt) -> belong to a method – Basically local! • Dies when method is done. • Declared in method heading. • Initialized through method call / account.deposit(500); • The 500 is the argument, and the amtis actually called the explicit parameter. • Default Initialization: Numbers to 0 & Object References to null.
public void deposit (double amt) { myBalance= myBalance + amt; } Implicit & Explicit Paramters (3.8) • Consider creating 2 new BankAcct objects: BankAcctmomAcct = new BankAcct(1000); BankAcctdadAcct = new BankAcct(500); • Now lets invoke deposit for each account: • momAcct.deposit(300); // myBalance = 1000 + 300 -> implies moms balance • dadAcct.deposit(300); // myBalance= 500 + 300 -> implies dads balance • Parameter var (amt) -> Explicit Paramter • Instance Fields (myBalance) -> Implicit Parameter • Relative to the invoking object ( data is unique) • Consider: • public void deposit(double amt) • { • this.myBalance = this.myBalance + amt; //No Different than above! • } • this refers to the implicit parameter!