Method Overloading

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

Answer:

Yes. The variable that follows the reserved word this is an instance variable (part of "this" object).

Method Overloading

Overloading is when two or more methods of a class have the same name but have different parameter lists. When a method is called, the correct method is picked by matching the actual parameters in the call to the formal parameter lists of the methods.

Review: another use of the term "overloading" is when an operator calls for different operations depending on its operands. For example + can mean integer addition, floating point addition, or string concatenation depending on its operands.

Say that two processDeposit() methods were needed:

  • One for ordinary deposits, for which there is no service charge.
  • One for other deposits, for which there is a service charge.
class CheckingAccount
{
  . . . .
  private int balance;

  . . . .
  public void processDeposit( int amount )
  {
    balance = balance + amount ; 
  }

  public void processDeposit( int amount, int serviceCharge )
  {
    balance = balance + amount - serviceCharge; 
  }

}

The above code implements these requirements. Here is an example main() method that uses both methods:

class CheckingAccountTester
{
  public static void main( String[] args )
  {
    CheckingAccount bobsAccount = new CheckingAccount( "999", "Bob", 100 );
    
    bobsAccount.processDeposit( 200 );       // statement A
    
    bobsAccount.processDeposit( 200, 25 );   // statement B
  }
}

There are two method calls, and two methods to pick from. A method call invokes to the method that matches it with both its name and its parameter list.

QUESTION 12:

Examine main().

Which method, processDeposit(int) or processDeposit(int, int) does each statement call?

  1. statement A calls
  2. statement B calls