I'm not sure I like the use of Runnable
in the context others have used. Typically, I think of Runnable
as something that will run in a thread, executor service, etc. And to back that up is the documentation:
The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread.
But making something that does the same thing from scratch is really simple and quick. We can make an abstract class that will hold the structure you need:
public abstract class AbstractClass
{
private void iniCall() { ... } // Could also be abstract
private void finalCall() { ... } // Could also be abstract
public void doTheThing()
{
iniCall();
foo();
finalCall();
}
public abstract void foo();
}
Of course you need to come up with better names, but that's the starting point. Then we have two options: instantiate an anonymous class built by extending this class, or creating a new concrete class. Here's the example of using an anonymous class:
AbstractClass a = new AbstractClass()
{
@Override
public void foo()
{
// Place an implementation here.
method(); // one example, based on the OP.
}
};
a.doTheThing();
And here's how you would do an actual class:
public class ConcreteClass extends AbstractClass
{
@Override
public void foo()
{
// Place an implementation here.
}
}
ConcreteClass c = new ConcreteClass();
c.doTheThing();
I mainly wanted to bring this up so that you could have a look at the 'anonymous class' paradigm, which is analogous to being able to pass functions as parameters. Other languages have pointers to functions, delegates, etc - well this is what Java has. The compiler will ensure that your anonymous class and concrete classes will have an implementation of foo
, or it won't compile, so it's not something you can just go 'oops' and forget to implement.