Question:
Is it possible to pass a method to another class,so that method can be called by that class at a later date?For example, in C you can pass an event handler to afunction, and that handler can be later called by that function if aspecific event occurs.
Answer:
This issue comes up frequently with object-oriented languagesand fortunately Java provides a very clean solution for accomplishingthis: Interfaces.
An interface is basically a collection of method definitions withoutthe implementations. A class is said to implement an interface whenit provides implementations for the methods listed in that interface.
For example, the Runnable interface in Java looks like this:
public interface java.lang.Runnable { public abstract void run(); }It specifies a single method called ‘run’ that doesn’t take anyarguments and doesn’t return anything. It’s just a specificationat this point — no body has been defined for the method.
When a class implements the Runnable interface, it has to providethe implementation for the run()
method as it sees fit. Forexample:
public class Foo implements Runnable { public void run() { // Foo’s implementation of run() goes here } }It just so happens that the
Thread
class can be initializedusing an object that implements the Runnable interface. Becauseclass Foo
implements the Runnable interface, you cancreate a Thread in this manner:Now the Thread class is guaranteed to be able to call theThread t = new Thread(newFoo());
run()
method of Foo
. Let’s see how this mechanism can solve your problem. Let’s say youhave a class Chef
and a class Food
. You wantclass Chef
to be able to call the cook()
methodin class Food
, and you somehow want to ‘pass’ thecook()
method in Food
to the Chef. Here’s how toaccomplish this:
// define an interface called cookable that // specifies the cook() method public interface Cookable { public abstract void cook(); } // Let class Food implement that interface // by providing the body for the cook() method public class Food implements Cookable { public void cook() { // get cooked } } // Let the Chef call cook() on the Cookable object it gets // All the Chef knows is that the object is Cookable. public class Chef { public makeDish(Cookable dish) { dish.cook(); } }Now, if you had a
Kitchen
class, you could easily have theChef
cook some food:Chef chefWang = new Chef(); Food cashewChicken = new Food(); chefWang.makeDish(cashewChicken); Food noodles = new Food(); chefWang.makeDish(noodles);Since
noodles
and cashewChicken
both implementthe Cookable interface, chefWang
can just call theircook()
methods and the dishes will be ready in no time.