Methods in Java: Overloading, Recursion, Static methods and the final keyword

We have already seen the basics of methods , the way it is created and the various ways it can be used in our programs. In this tutorial, we shall see other ways in which the methods can be used to meet the programmer’s desire.

Method Overloading

Method overloading refers to the creation of more than one methods with the same name in the same class. Method overloading is a way that demonstrates polymorphism(or more accurately static polymorphism) in Java. This flexibility of the methods comes with one restriction. The methods that share the same name must not have the same parameter. They must differ in this aspect to preserve the identity of the method.

The methods can either have a different number of parameters, or different data type of parameters or can have a sequential change in parameters with different data types. The compiler must know which method is being called. Also, the methods can have different return types but it is not enough for the compiler to distinguish between the methods. Here is an example of method overloading:

/**
 * This program shows the use of method-overloading.
 */

package com.codingeek.java.Methods;

public class MethodOverloading {
    /*
     *The following method takes a char and an integer value from the main() method.
     */
    void display(char a, int b) {

        System.out.println("The values are : " + a + " , " + b);
    }

    /*
     *The following method takes an integer value from the main() method.
     */
    void display(int a) {

        System.out.println("The value is : " + a);
    }

    /*
     *The following method takes a double value from the main() method.
     */
    void display(double a) {

        System.out.println("The value is : " + a);
    }

    /*
     *The following method takes a char value from the main() method.
     */
    void display(char a) {

        System.out.println("The value is : " + a);
    }

    public static void main(String[] args) {

        MethodOverloading ob = new MethodOverloading();

        //calling the same methods with different parameters.
        ob.display(5);
        ob.display('B');
        ob.display(56.9);
        ob.display('C', 45);
    }
}

Output:-
The value is : 5
The value is : B
The value is : 56.9
The values are : C , 45

Recursion

Recursion is the process in which a function calls itself and the method that calls itself is known as a recursive function. This means that the method call statement is present in the body of the method itself.

When using recursion, it is important to put a terminating condition just as in for loop to pass the control back to the calling method. If there’s no terminating condition then the function will run repeatedly just like an infinite loop. It is also important to note that recursion is an important application of stack. Here is an example of a recursive program:

/**
 * The following program prints the factorial of a number in the range specified by the user.
 * This program uses recursion.
 */

package com.codingeek.java.Methods;

import java.util.Scanner;

public class RecursionDemo {

    /*
     *This is the recursive method which calculates the factorial of a number.
     */
    int calcFactorial(int x) {

        if (x == 0 || x == 1) {
            return 1;
        } else {
            return x * calcFactorial(x - 1); //decreases the value of x for every call
        }
    }

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        RecursionDemo ob = new RecursionDemo();

        int a, b;
        System.out.println("Enter the range :");
        a = in.nextInt();
        b = in.nextInt();

        for (int i = a; i <= b; i++)
        {
            //calling the function calcFactorial() to calculate the factorial of the numbers individually
            System.out.println("The factorial of " + i + " = " + ob.calcFactorial(i));
        }
    }
}

Output:-
Enter the range :
4
8
The factorial of 4 = 24
The factorial of 5 = 120
The factorial of 6 = 720
The factorial of 7 = 5040
The factorial of 8 = 40320

Static methods

The methods that have the static keyword in their method definition are known as static methods. They add special utility to methods, such as a static method can be called by another static method directly, i.e. without the creation of an object.

And a static method is accessed by the compiler first. This is the reason why we declare the main() method as static. But using static comes with the restriction that it cannot make use of this or super keyword in any way. Here is an example of a static method :

/**
 * This program shows the use of static methods.
 */

package com.codingeek.java.Methods;

public class StaticMethodDemo {

    /**
     * The following method is defined as static so it can be
     * called by the main() method directly since main() method is also declared as static
     */
    static void meth() {
        System.out.println("Inside the static method meth()");
    }

    public static void main(String[] args) {
        meth(); //calling the static method meth()
    }
}

Output:-
Inside the static method meth()

Final Keyword

The final keyword is a non-access specifier which is used to prevent the value or the content of the classes, fields, and methods declared as final to be changed. It has different purposes in different contexts.

  • A variable declared as final: A variable declared as final will have its value fixed. According to the convention, the fields declared as final are usually written in capitals using an underscore to separate words. Local variables can also be declared as final.
  • A method declared as final: A method declared as final cannot be overridden. Eg Object class which has a lot of final methods which are not meant to be overwritten.
  • A class declared as final: A class that is declared as final cannot be inherited by another class. It is useful when creating immutable(cannot be extended) classes. Eg: String class.

A field that is declared as final behaves as a constant and must be initialized at the time of declaration either by directly assigning the value or by assigning the value with the help of a constructor(in the case of variables).

The examples of the declaration of a final class, method, and variable are shown below:

/**
  * This is a final class.
  */
  public final class ClassName {
     final int YES = 1;  //This is a final variable.
     final int NO = 0;  //This is a final variable.
   
     //This is a final method.
     public final void getResponse() {
        //body
     }

So, that’s all for this tutorial. Hope this helps and you like the tutorial. Do ask for any queries in the comment box and provide your valuable feedback. Do come back for more because learning paves way for a better understanding.

Keep Coding!! Happy Coding!! 🙂

Recommended -