1 / 2

Variable Types & Scope(Lifetime of Variable)

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.

sylvie
Download Presentation

Variable Types & Scope(Lifetime of Variable)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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.

  2. 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!

More Related