Chapter 4

Class Methods

Methods contain code for actions or functions a class can perform. In this lesson you’ll learn how to declare and call them.

Method Arguments

Each class method performs some functionality, such as calculating tax, placing an order, or starting the car. If a method requires some external data to perform its function, such data can be provided in the form of arguments or parameters, as in the function adjustForStudents() shown in Listing 3-5, which has one argument: stateTax.

In the method signature you need to declare the data type and the name of each argument, for example:

int calcLoanPayment(int amount, int numberOfMonths, String state){
   // Your code goes here

When you call a function, Java run time tries to find the function that has been declared with the specified signature. For example, if you try to call the preceding function like this:

calcLoanPayment(20000, 60);

Java compiler will give you an error complaining that no calcLoanPayment() function has been found that expects just two arguments.

Method Overloading

If you want to allow the calling of a function with different numbers of arguments, you need to create multiple versions of this function. For example, you can create a function that will use the state of New York to spare developers from providing the state as an argument. If most of the loan calculation is done for New Yorkers, such a function may be a good idea.

 int calcLoanPayment(int amount, int numberOfMonths){    // Your ...

Get Java® Programming 24-Hour Trainer now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.