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

public class CheckingAccount
{
  private String accountNumber;
  private String accountHolder;
  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
  }

}

A method's statements can see the instance variables of their object. They cannot see the parameters and local variables of other methods. Look again at the CheckingAccount class.

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 parameter list 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?)


go to previous page   go to home page   go to next page