Home

 › 

Articles

 › 

6 Types of Methods in Java and When to Use Each

Types of Methods in Java

6 Types of Methods in Java and When to Use Each

Much like functions in Python and C++, methods in Java are blocks of code used to perform particular tasks, such as processing or calculating. Methods can function without returning an output, but generally, this is recommended. They’re defined inside classes, and allow you to reuse code without having to type it again. Methods are executed when we call them and can contain arguments. Today, we’re going to look at the different types of methods in Java and show when you may want to use them.

How to Use a Method

To use a method in Java, you need to declare and define the method. Generally, this takes the following form of a method header:

<access> <type of return> <name of method> (parameters)
{
//body of method
}

For example, let’s take the following header:

public static int sum(int num1, int num2) {
    int result = num1 + num2;
    return result;
}

Here, we have the access specifier as “public.” This means that all classes can access the method. Alternative types include private (only accessible in the class it has been defined in), protected (accessible within the same package), or default (default specifier is used if one isn’t chosen.)

The return type is “int”, meaning an integer value is returned. Other types include objects, arrays, or void (no value is returned.)

The method name is “sum”, which is used for adding values together.

The parameters are “int num1” and “int num2”, which designate two numbers.

The method body indicates a sum of the two integer values and a return of the result to the console.

How to Create and Name a Method

When creating a method, you can choose between creating an instance method and a static method. Instance methods belong to a class object and can only be called on an instance of the class, whereas static methods belong to the class and can be called on the class itself.

To create a static method, you would use the “static” keyword before the return type. To create an instance method, you don’t need a keyword, but you do need to create an instance first. Generally, you want to use instance methods when the behavior depends on the state of the object, and static methods when the behavior doesn’t depend on the object’s state.

To name your method, you must keep the following rules in mind:

  • The name must be a verb, and in lowercase
  • If the name contains two or more words, the first word must be a verb followed by a noun or adjective
  • In such a case, subsequent words after the first must be capitalized.

Types of Methods in Java

While there are many methods you can use in Java, they fall into two camps: Predefined methods and user-defined methods. Next, we’ll take a look at these with an example.

Predefined Methods

These are also known as standard library methods since they’re already defined within the Java libraries. To use them, we only need to call them in our code. Examples of predefined methods are “sqrt()”, “compareTo()”, “equals()” and “length()”. An example to illustrate predefined methods is shown next.

public class PredefinedMethodExample {
    public static void main(String[] args) {
        String str = "Hello World!";
        int length = str.length(); // length() is a predefined method in the String class
        System.out.println("The length of the string is: " + length);
    }
}

In this example, we declare the public class “PredefinedMethodExample” containing the “main()” method. This is a public static method that doesn’t return a value, with the “String” array. An object within the array called “Hello World!” is created, and the “length()” method is called to return the number of characters within this string. This is printed to the console, as shown in the image below.

An example of a predefined method in Java.

©History-Computer.com

User-defined Methods

These types of Java methods are written by a programmer, and can therefore be modified according to your particular needs for your program. For example, consider the following code:

public class UserDefinedMethodExample {
    public static void main(String[] args) {
        int result = multiply(5, 7); 
        System.out.println("The result of multiplication is: " + result);
    }

    public static int multiply(int num1, int num2) {
        int product = num1 * num2;
        return product;
    }
}

First, we’ve declared the public class “UserDefinedMethodExample”, which contains the public static method “main()” which returns no value inherently. A string is created, “The result of multiplication is:”, and the result of the calculation is added to the end. The user-defined method is defined as the multiplication of the integer values, in this case, 5 and 7. The value that’s returned is assigned to the variable “result”, and the output is printed as shown below.

When it comes to user-defined methods, there can be many kinds, as well as the aforementioned static and instance methods. These include:

  • Constructors
  • Getter and setter methods
  • Abstract methods
  • Final methods
  • and Synchronized methods.

Let’s look at these in more detail.

A simple user-defined method.

©History-Computer.com

Constructors

Constructor methods are called such because they’re used to “construct” class objects and initialize them. They have the same name as the class, but they don’t have a return type. Typically, they’re used to initialize variables and enforce constraints on how objects are created. For example, we have the following code:

public class ConstructorExample {
    private String make;
    private String model;
    private int year;

    public ConstructorExample(String make, String model, int year) {
        this.make = make;
        this.model = model;
        this.year = year;
    }

    public void startEngine() {
        System.out.println("The engine of the " + make + " " + model + " is starting.");
    }
    
    public static void main(String[] args) {
        ConstructorExample myCar = new ConstructorExample("Toyota", "Corolla", 2021);
        myCar.startEngine();
    }
}

We start by declaring the public class, “ConstructorExample”, and then define two private string variables and one private int variable.

Then, we define a public constructor function, “ConstructorExample”, that takes three arguments. The next three lines use the “this” keyword to assign the values of the parameters to the variables.

Next, we define the public method “startEngine”, which has no arguments.

The next line prints out a message including the “make” and “model” variables.

We then define a public function, “main()”, that takes an array of strings as an argument.

Finally, we create an instance of the “ConstructorExample” class and set it with the values “Toyota”, “Corolla” and “2021”, and call the “startEngine” function to print the result on the console. This is shown in the screenshot below.

A constructor is used to initialize the values of variables.

©History-Computer.com

Getter and setter methods

These are both user-defined instance methods. While “getter” is used to access values of private variables in a class, “set” is used to modify these values. They’re used a lot in object-oriented programming to enforce encapsulation, which restricts access to class variables to certain methods. We can illustrate both methods with the following example:

public class GetterAndSetterExample {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public static void main(String[] args) {
        GetterAndSetterExample example = new GetterAndSetterExample();
        example.setName("John");
        example.setAge(30);
        System.out.println("Name: " + example.getName());
        System.out.println("Age: " + example.getAge());
    }
}

Here, we declare a public class, “GetterAndSetterExample”, and private instance variables of “name” and “age”, which are string and int variables respectively.

Next, we define the “getName()” method, which returns the string variable.

After this, we define the “setName()” method, which takes the string parameter. The “this” keyword sets the value of the variable to the value of the parameter passed to the previous method.

The next method, “getAge()”, returns the int variable.

Next, the “setAge()” method takes the int parameter. As before, the “this” keyword sets the value of the variable to the value of the parameter passed to the “setAge()” method.

The “main()” method follows, which takes the “String” parameter named “args”, and is where the program begins.

We then create a new instance of the “GetterAndSetterExample” class, and assign a variable called “example.”

After that, we use the “setName()” method to set the object’s name to “John.” Subsequently, we call the “setAge()” method to set the age of the object to “30.”

Finally, we print the “name” variable value and the “age” variable value on the console. You can see this in the image below.

The getter and setter methods are illustrated.

©History-Computer.com

Abstract methods

Another example of a user-defined instance method, an abstract method, is declared within a class but without implementation. But it’s worth saying, abstract methods can potentially be predefined instead. Generally, they’re used to declare a method that is to be implemented by subclasses rather than this class. In this way, we can create a standardized method signature in the parent class, which can then be further customized within each subclass as needed.

An example of an abstract method is shown in the code that follows. Note that, because this code contains multiple public classes, these must be saved in separate files – namely “Animal”, “Cat”, “Dog” and “AnimalSounds.”

public abstract class Animal {
    public abstract void makeSound();
}
public class Cat extends Animal {
    public void makeSound() {
        System.out.println("Meow");
    }
}
public class Dog extends Animal {
    public void makeSound() {
        System.out.println("Woof");
    }
}
public class AnimalSounds {
    public static void main(String[] args) {
        Animal myCat = new Cat();
        Animal myDog = new Dog();
        myCat.makeSound(); // Output: Meow
        myDog.makeSound(); // Output: Woof
    }
}

We’re defining a few different classes here. First, the public class “Animal” has the abstract method “makeSound”, with no implementation.

The “Cat” class extends the “Animal” class, with a public method “makeSound()”. This overrides the method from the previous class. We then print the output.

In the “Dog” class, we extend the “Animal” class again and override it with another “makeSound()” method. As before, we print the output on the console.

Finally, we have the “AnimalSounds” class, which defines the “main()” method and creates new “Cat” and “Dog” objects, assigning the reference variables from “Animal” as “myCat” and “myDog” respectively. The “makeSound()” methods are called and the output is visible in the console as seen below.

The class AnimalSounds using the abstract method makeSound().

©History-Computer.com

Final methods

Final methods are in contrast to abstract methods, in that they cannot be overridden by a subclass. This type of Java method is used when you need a method to behave predictably and not be changed by a subclass. This helps to speed up the program since it can tell that the implementation is permanent. It also helps ensure code stability and compatibility, especially when sharing code with other developers and libraries. Final methods can be predefined or user-defined. An example of a final method would be as follows:

public class Animal {
    public final void makeSound() {
        System.out.println("The animal makes a sound.");
    }
}
public class Dog extends Animal {
    public void makeSound() {  // This will produce a compile-time error
        System.out.println("The dog barks.");
    }
}

As we can see in the screenshot, we’ve encountered a compilation error with this code. This is because the “Dog” class is attempting to override the “makeSound()” method but this is declared as a final method within the “Animal” class.

If we want to keep the final method in the “Animal” class, we can fix this by changing the name of the method in the “Dog” class. By doing this, the method won’t attempt to override the first method. This is shown in the second screenshot, where we’ve changed the second “makeSound” method to “bark” instead. We also must put the classes in separate files, as with the previous method.

The final method illustrated.

©History-Computer.com

Synchronized methods

The last type of method in Java we’re going to explore is synchronized methods. These are used when you don’t want multiple threads to access the same code or method simultaneously and can be predefined as well as user-defined. When a thread enters the code, it “locks” the code, meaning that other threads can’t access it until it’s released by the first thread. This ensures atomic execution, meaning uninterruptable. An example of a synchronized method is shown next. Classes are in separate files, as before.

public class SynchronizedCounter {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public synchronized void decrement() {
        count--;
    }

    public synchronized int getCount() {
        return count;
    }
}
public class SynchronizedExample {
    public static void main(String[] args) {
        SynchronizedCounter counter = new SynchronizedCounter();

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                counter.increment();
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                counter.decrement();
            }
        });

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Count: " + counter.getCount());
    }
}

In the first block of code, we declare the class “SynchronizedCounter” with three synchronized methods, “increment()”, “decrement()” and “getCount()”.

The “Count” private variable starts at 0. “Increment” and “decrement” increase and decrease the “count” variable by 1 respectively, while “getCount” gets the current value. This is then returned.

For the second code block, we declare the class “SynchronizedExample”, with the method “main()”. This takes an array of string objects as an argument.

An instance of the class is then created, and a variable is assigned as “counter.”

Then, we create an instance of the “Thread” class, and assign a variable of “t1.” The “for” loop calls the “increment()” method 10,000 times on the “counter” object.

After that, another instance of the class is created, called “t2.” This calls the “decrement()” method 10,000 times.

Finally, the threads are commenced with the following code but are carried out separately as per the synchronized methods.

The result is then printed on the console, as seen below. The result is 0, because we have first incremented “count” by 10,000 and then decremented it by 10,000. This gives a net result of 0.

Types of Methods in Java
A class using synchronized methods.

©History-Computer.com

Wrapping Up

Methods in Java are similar to functions in other programming languages. The main types of methods in Java are predefined or user-defined methods, and within these, there are static and instance methods. Static methods belong to a class, whereas instance methods require an instance of the class to be created. Most common method types fall into the user-defined instance category, such as getter and setter, constructor, abstract, final, and synchronized, although the latter three can also be predefined. In order to develop robust and scalable programs, understanding the various methods in Java is key.

Frequently Asked Questions

What are the method types in Java?

All methods fall into either predefined or user-defined methods, and can be either static or instance methods.

 

 

What are predefined methods?

These are methods that are predefined in a library, so they don’t need to be created by a user.

What are instance and static methods?

Instance methods require an instance of a class to be created, so depend on the state of the object. On the other hand, static methods belongs to a class, and can be called using the class name. As such, they don’t depend on the state of the object.

What are getter and setter methods?

Getter and setter are used to access and modify variable values within a class respectively.

What are constructor methods?

These are methods used to create class objects, and have the same name as the class. Constructors are automatically called when the object is created, and often used in conjunction with other methods such as getter and setter.

What are abstract methods?

Abstract methods are declared in a class but with no implementation. This is provided by the class which extends the abstract class, which is known as the concrete class.

What are final methods?

These are methods which cannot be overridden by any methods in a subclass. This ensures the behavior of a method isn’t modified, helping to ensure stability and compatibility.

What are synchronized methods?

Synchronized means that the methods can only be accessed by one thread at a time, so the execution is uninterruptable. This helps to prevent race conditions, which can lead to unpredictable outcomes.

Can instance methods be predefined?

Yes, instance methods can predefined as part of a Java library. Examples would be the length(), equals() and substring() instance methods that are predefined within the String class.

Is a constructor the same thing as a method?

These are similar terms, except a constructor is a special type of method. While a method is code that performs a defined task, constructors are used to create and initialize objects of classes. Methods can also have any name and a return type, whereas constructors share the class name and have no return type. Methods must also be called manually, where constructors are called automatically upon creation of the class object.

What does method overloading mean?

Method overloading is a feature where classes can have several methods with identical names but differing parameters. The method which is called is determined by the compiler, usually because of the nature of the arguments that are passed. This can help enhance code readability and offer several solutions to a task.

To top