How to Create Callback Functions in Java

Sheeraz Gul Feb 02, 2024
  1. Use Interface to Create Callback Functions in Java
  2. Create Synchronous and Asynchronous Callback Functions in Java
How to Create Callback Functions in Java

The callback feature is used in event-driven programming. A reference is passed to a function called when a corresponding event occurs.

We use interfaces to achieve the callback in Java because it does not support the function pointer.

This tutorial demonstrates how to create and use callback functions in Java.

Use Interface to Create Callback Functions in Java

An interface in Java is an abstract type that specifies the class’s behavior. It is the blueprint class of a class.

We can create one interface and multiple classes to demonstrate the callback in Java.

The code below implements one interface and four classes to calculate an employee’s salary. To call the function, we pass the reference of the interface; this is the callback.

The code calculates the net salary by deducting 10 percent from the gross salary. See output for each class; we run the code four times.

import java.util.Scanner;
// Create interface
interface Salary {
  double Person_Salary();
}

// Class for Jack's Salary
class Jack implements Salary {
  public double Person_Salary() {
    return 5000.0;
  }
}

// Class for Michelle's Salary
class Michelle implements Salary {
  public double Person_Salary() {
    return 4000.0;
  }
}
// Class for Jhonny's Salary
class Jhonny implements Salary {
  public double Person_Salary() {
    return 3000.0;
  }
}

// Class for Mike's Salary
class Mike implements Salary {
  public double Person_Salary() {
    return 3500.0;
  }
}

class Employee_Salary {
  public static void main(String[] args)
      throws ClassNotFoundException, IllegalAccessException, InstantiationException {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the Employee Name: ");

    // name of the employee
    String Employee = sc.next();

    // Store the employee name in an object temp
    Class temp = Class.forName(Employee);

    // Create the new object of the class whose name is in temp
    // Interface Salary's reference is now referencing the new object created above
    Salary reference = (Salary) temp.newInstance();

    // Call the method to calculate net salary and pass interface reference - this is a callback.
    // Here reference refers to the function Person_Salary() of both Jack and Michelle's classes

    Calculate_Salary(reference);
  }
  static void Calculate_Salary(Salary E_Salary) {
    // calculate Salary Deduction Which is 10 percent
    double salary_deduction = E_Salary.Person_Salary() * 0.1;

    // The gross salary
    double gross_salary = E_Salary.Person_Salary();

    // Calculate the net salary
    double net_salary = gross_salary - salary_deduction;

    // Show the net salary
    System.out.println("The Net Salary of Employee is =" + net_salary);
  }
}

Output:

Enter the Employee Name:
Jack
The Net Salary of Employee is =4500.0

Enter the Employee Name:
Michelle
The Net Salary of Employee is =3600.0

Enter the Employee Name:
Jhonny
The Net Salary of Employee is =2700.0

Enter the Employee Name:
Mike
The Net Salary of Employee is =3150.0

Create Synchronous and Asynchronous Callback Functions in Java

Synchronous Callback

The code execution will wait or block the event for the synchronous callback until it returns a response. The callback will perform all its work before returning to the call statement.

The synchronous sometimes appear to lag. The code below implements a simple synchronous task to callback functions.

// Create Interface
interface Delftstack {
  void delftstack_event();
}
class Delftstack_Two {
  // Delftstack Field
  private Delftstack Delft;

  // setting the register_delftstack function
  public void register_delftstack(Delftstack Delft) {
    this.Delft = Delft;
  }

  // This is our synchronous task
  public void Hello_Delftstack() {
    // perform any operation
    System.out.println("Hello! This is delftstack callback from before the synchronous task.");

    // check if listener is registered.
    if (this.Delft != null) {
      // invoke the callback method of class A
      Delft.delftstack_event();
    }
  }
  // Main
  public static void main(String[] args) {
    Delftstack_Two Demo_Object = new Delftstack_Two();
    Delftstack Delft = new Delftstack_One();
    Demo_Object.register_delftstack(Delft);
    Demo_Object.Hello_Delftstack();
  }
}

class Delftstack_One implements Delftstack {
  @Override
  public void delftstack_event() {
    System.out.println("Hello! This is delftstack callback from after the synchronous task.");
  }
}

Output:

Hello! This is delftstack callback from before the synchronous task.
Hello! This is delftstack callback from after the synchronous task.

Asynchronous Callback

On the other hand, the asynchronous callback doesn’t block the code from execution.

In Java, we need to create a thread to develop an asynchronous task and implement the callback inside. When the call returns from the event, it returns to the callback function for the asynchronous.

The code example below implements a simple asynchronous task to callback functions.

// Create Interface
interface Delftstack {
  void delftstack_event();
}

class Delftstack_Two {
  // Delftstack Field
  private Delftstack Delft;

  // setting the register_delftstack function
  public void register_delftstack(Delftstack Delft) {
    this.Delft = Delft;
  }
  // The Asynchronous
  public void Hello_Delftstack() {
    // An Asynchronous must be executed in a new thread
    new Thread(new Runnable() {
      public void run() {
        System.out.println("Hello! This is delftstack operation inside the asynchronous task.");

        // check if Delft is registered.
        if (Delft != null) {
          // invoke the callback method of class A
          Delft.delftstack_event();
        }
      }
    }).start();
  }

  // Main
  public static void main(String[] args) {
    Delftstack_Two Demo_Object = new Delftstack_Two();
    Delftstack Delft = new Delftstack_One();
    Demo_Object.register_delftstack(Delft);
    Demo_Object.Hello_Delftstack();
  }
}

class Delftstack_One implements Delftstack {
  @Override
  public void delftstack_event() {
    System.out.println("Hello! This is delftstack callback from after the asynchronous task.");
  }
}

Output:

Hello! This is delftstack operation inside the asynchronous task.
Hello! This is delftstack callback from after the asynchronous task.
Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

Related Article - Java Function