Java OOP: Class Methods Tutorial
In this Java tutorial we learn how to group sections of program functionality into smaller reusable units called methods.
We cover how to define and use non-static and static methods, how to add parameters and how to return values, along with control, from them. We also cover the ‘this’ construct and how it refers to the calling object as well as how to construct objects with initial values.
Lastly, we quickly discuss and link to the Lambdas lesson and do a quick little challenge.
- What is a method
- How to define a method in Java
- How to use (invoke/call) a method in Java
- How to add parameters to a method in Java
- How to return a value from a method in Java
- Static methods in Java
- Lambda expressions (anonymous methods) in Java
- Mini challenge
- The ‘this’ construct in Java
- How to construct an object with values in Java
- Summary: Points to remember
What is a method
Methods allow us to group sections of our code into a smaller, reusable units.
As an example, let’s consider some simple logic.
The simple logic in the example above will check if a number is even or odd.
Our application may require this evaluation multiple times throughout the code. We don’t want to repeat ourselves and retype this logic each time we want to check a number.
Instead, we want to separate the logic into a unit that we can more easily use over and over, anywhere in our code. These units are called methods.
How to define a method in Java
A method definition consists of the following parts.
- An access modifier
- A return type
- A name
- Parameters (optional)
- A body with one or more statements
- A returned value (optional)
In Java, methods can only be defined in classes, we cannot define standalone methods.
We’ll start with the most basic method and add features as we go.
In the example above, we create a class called ‘Logger’ with a method inside called ‘logMessage’. All it does is print some text to the console.
Typically we would create each class in its own file, but to keep things simple, we just defined the ‘Logger’ class below the ‘Program’ class.
Let’s break down the method definition step by step.
- For the access modifier, we used public to allow access to the function from any other class. We cover access modifiers in detail in the OOP: Encapsulation & Access Modifiers lesson .
- For the return type, we used void. When a function doesn’t return a value, we always specify the return type as void.
- Our method has no parameters so we left the parameter list empty. The parentheses must always be included even if the method doesn’t have any parameters.
- In the function body we just print some text to the console.
- Because our function doesn’t return anything, we can omit the return keyword.
Now if we go ahead and run the script, nothing happens. That’s because we’ve defined the method, but we haven’t used anywhere it yet.
How to use (invoke/call) a method in Java
To use a method, we need to tell the compiler that we want the method to execute the code in its body once. We do this by invoking the method, otherwise known as calling it.
To call a method we write its name, its parameter list and terminate the statement with a semicolon.
But, because the method is inside a class, we need to instantiate an object and call the method through dot notation. Like we did with parameters.
Defining Methods
The only required elements of a method declaration are the method’s return type, name, a pair of parentheses, () , and a body between braces, <> .
More generally, method declarations have six components, in order:
- Modifierssuch as public , private , and others you will learn about later.
- The return typethe data type of the value returned by the method, or void if the method does not return a value.
- The method namethe rules for field names apply to method names as well, but the convention is a little different.
- The parameter list in parenthesisa comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses, () . If there are no parameters, you must use empty parentheses.
- An exception listto be discussed later.
- The method body, enclosed between bracesthe method’s code, including the declaration of local variables, goes here.
Modifiers, return types, and parameters will be discussed later in this lesson. Exceptions are discussed in a later lesson.
Definition: Two of the components of a method declaration comprise the method signaturethe method’s name and the parameter types.
The signature of the method declared above is:
calculateAnswer(double, int, double, double)
Naming a Method
Although a method name can be any legal identifier, code conventions restrict method names. By convention, method names should be a verb in lowercase or a multi-word name that begins with a verb in lowercase, followed by adjectives, nouns, etc. In multi-word names, the first letter of each of the second and following words should be capitalized. Here are some examples:
run runFast getBackground getFinalData compareTo setX isEmpty
Typically, a method has a unique name within its class. However, a method might have the same name as other methods due to method overloading.
Overloading Methods
The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists (there are some qualifications to this that will be discussed in the lesson titled «Interfaces and Inheritance»).
Suppose that you have a class that can use calligraphy to draw various types of data (strings, integers, and so on) and that contains a method for drawing each data type. It is cumbersome to use a new name for each methodfor example, drawString , drawInteger , drawFloat , and so on. In the Java programming language, you can use the same name for all the drawing methods but pass a different argument list to each method. Thus, the data drawing class might declare four methods named draw , each of which has a different parameter list.
public class DataArtist < . public void draw(String s) < . >public void draw(int i) < . >public void draw(double f) < . >public void draw(int i, double f) < . >>
Overloaded methods are differentiated by the number and the type of the arguments passed into the method. In the code sample, draw(String s) and draw(int i) are distinct and unique methods because they require different argument types.
You cannot declare more than one method with the same name and the same number and type of arguments, because the compiler cannot tell them apart.
The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.
Java Methods
A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also known as functions.
Why use methods? To reuse code: define the code once, and use it many times.
Create a Method
A method must be declared within a class. It is defined with the name of the method, followed by parentheses (). Java provides some pre-defined methods, such as System.out.println() , but you can also create your own methods to perform certain actions:
Example
Create a method inside Main:
Example Explained
- myMethod() is the name of the method
- static means that the method belongs to the Main class and not an object of the Main class. You will learn more about objects and how to access methods through objects later in this tutorial.
- void means that this method does not have a return value. You will learn more about return values later in this chapter
Call a Method
To call a method in Java, write the method’s name followed by two parentheses () and a semicolon;
In the following example, myMethod() is used to print a text (the action), when it is called:
Example
Inside main , call the myMethod() method:
public class Main < static void myMethod() < System.out.println("I just got executed!"); >public static void main(String[] args) < myMethod(); >> // Outputs "I just got executed!"
A method can also be called multiple times:
Example
public class Main < static void myMethod() < System.out.println("I just got executed!"); >public static void main(String[] args) < myMethod(); myMethod(); myMethod(); >> // I just got executed! // I just got executed! // I just got executed!
In the next chapter, Method Parameters, you will learn how to pass data (parameters) into a method.