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.
Can we call a method on «this» keyword from a constructor in java?
The “this ” keyword in Java is used as a reference to the current object, with in an instance method or a constructor. Using this you can refer the members of a class such as constructors, variables and methods.
Calling a method using this keyword from a constructor
Yes, as mentioned we can call all the members of a class (methods, variables, and constructors) from instance methods or, constructors.
Example
In the following Java program, the Student class contains two private variables name and age with setter methods and, a parameterized constructor which accepts these two values.
From the constructor, we are invoking the setName() and setAge() methods using «this» keyword by passing the obtained name and age values to them respectively.
From the main method, we are reading name and, age values from user and calling the constructor by passing them. Then we are displaying the values of the instance variables name and class using the display() method.
public class Student < private String name; private int age; public Student(String name, int age)< this.setName(name); this.setAge(age); >public void setName(String name) < this.name = name; >public void setAge(int age) < this.age = age; >public void display() < System.out.println("Name of the Student: "+this.name ); System.out.println("Age of the Student: "+this.age ); >public static void main(String args[]) < //Reading values from user Scanner sc = new Scanner(System.in); System.out.println("Enter the name of the student: "); String name = sc.nextLine(); System.out.println("Enter the age of the student: "); int age = sc.nextInt(); //Calling the constructor that accepts both values new Student(name, age).display(); >>
Output
Rohan Enter the age of the student: 18 Name of the Student: Rohan Age of the Student: 18