Beruflich Dokumente
Kultur Dokumente
The methods which are called implicitly by the software are known as callback
methods. That is, callback methods are called automatically. Programmer writes them but
never call them. They are called by the software at an appropriate time when required for the
smooth execution of the program. Let us explain further through examples.
Examples of Callback methods in Java
1. The best example is main() method in Java. We write the main() method and fill it with
some code but we never call it. It is automatically called by JVM (here, JVM is the
software) to start the execution of an application.
2. The five life cycle methods of Applet are init(), start(), paint(), stop() and destroy(). These
methods are called by the Browser (here, the Browser is the software) whenever it thinks
needed for the smooth execution of applet.
3. run() method of thread. It is called implicitly whenever a thread starts its execution.
4. service() method of Servlet. When the servlet is loaded by the Web container, it calls
service() method automatically.
In the case of Event-driven programming, we pass a reference to a function which will get called
when an event occurs. This mechanism is termed as a callback. Java does not support function
pointers. So we can not implement the same direction. But using interfaces we can achieve the
same very easily.
In the example below, we've made a callback when a button is clicked. See the steps:
1. Create an interface ClickEventHandler with a single method handleClick().
2. Create a ClickHandler class which implements this interface ClickEventHandler.
3. Create a Button class which will call ClickHandler when it's click method is called.
4. Test the application.
Example
Live Demo
//Step 1: Create an interface for the callback method
interface ClickEventHandler {
public void handleClick();
}