4.4 Method Overloading

Method overloading is a feature common to most object-oriented programming languages and is one aspect of polymorphism. This allows us to have methods with the same identifier but with different argument lists. The argument lists can have a different ordering of data types or can have a different number of arguments. In the Account class, in addition to the deposit method we have already seen (lines 12–14), we could also add a second deposit method that prints the balance if it exceeds a supplied level.

public void deposit(double amount, double level)
{
balance = balance + amount;
if (balance > level)
{
System.out.println(''Current balance = " + balance);
}
}



In the CreateAccounts application, the following statements would invoke each
deposit method in turn:

fredsAccount.deposit(100);
fredsAccount.deposit(100, 120);


The Java compiler checks that the data types of the method being invoked match those of the method in the class. In this way, the correct method will be invoked.


Constructors can also be overloaded. In addition to the existing constructor in the Account class (lines 6–10), we can add a second, which takes only the account number and name as arguments and sets the balance to 10.

public Account(int no, String name)
{
accountNo = no; accountName = name; balance = 10;
}


In the CreateAccounts application, the following statements would create two objects,fredsAccount and billsAccount, using each constructor in turn:

Account fredsAccount = new Account(123, "Fred", 50);
Account billsAccount = new Account(456, "Bill");

No comments:

Post a Comment