What Statements See

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Can the toString() method see the object's instance variables, such as balance?

Answer:

Yes.

What Statements See

Statements of a method can see the object's instance variables and the object's other methods. They cannot see the parameters and local variables of other methods. Here is another look at the CheckingAccount class:

class CheckingAccount
{
  . . . .
  private int balance;

  . . . .
  
  public void  processDeposit( int amount )
  { // scope of amount starts here
    balance = balance + amount ;      
    // scope of amount ends here
  }

  public void processCheck( int amount )
  { // scope of amount starts here
    int charge;

    incrementUse();
    if ( balance < 100000 )
      charge = 15; 
    else
      charge = 0;

    balance =  balance - amount - charge  ;
    // scope of amount ends here
  }

}

Two methods are using the same identifier, amount, for two different formal parameters. Each method has its own formal parameter completely separate from the other method. This is OK. The scopes of the two parameters do not overlap so the statements in one method cannot "see" the formal parameter of the other method.

For example the statement

balance =  balance - amount - charge  ;

from the second method can only see the formal parameter of that method. The scope of the formal parameter of the other method does not include this statement.

Of course, the formal parameters of any one method must all have different names.

QUESTION 6:

Could the two formal parameters (of the two methods) named amount be of different types? (For example, could one be an int and the other a long?)