Lesson 4Class Methods and Constructors
Methods contain code for actions or functions a class can perform. Although you started working with methods in previous lessons, in this lesson you find out how to work with them in detail. You also get familiar with a special type of method called a constructor.
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 method 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, the following method has three arguments: two of them are the int
data type and one is String
:
int calcLoanPayment(int amount, int numberOfMonths, String state){ // Your code goes here }
When you call (or invoke) a method, the Java run time tries to find the method that has been declared with the specified signature. For example, if you try to call the preceding method like this:
calcLoanPayment(20000, 60);
the 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 method with different numbers of arguments, you need to create multiple versions of this method. For example, you can create a method ...
Get Java Programming 24-Hour Trainer, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.