views:

95

answers:

3

Hi, I have a question.

Somebody, who was working on my code before me, created some method and passed Runnable as parameter, more likely:

void myMethod(Runnable runnable){ runnable.run(); }

Then calling myMethod out of main looks like:

public static void main(String args[]) 
{ try 
{ myMethod(new Runnable(){ public void run() { //do something...; }}); } 
catch (Throwable t) { } }

So, to supply parameter to myMethod I need to instantiate object of (in this case anonymous) class implementing Runnable.

My question is: is it necessary to use Runnable in this example? Can I use any different interface? I mean I can create new interface with single method i.e.

interface MyInterface{ void doThis(); }

then change look of myMethod: void myMethod(MyInterface myObject){ myObject.doThis(); }

And of course client too:

public static void main(String args[]) { 
try { myMethod(new MyInterface (){ public void doThis() 
{ //do something...; }}); } 
catch (Throwable t) { } }

Or maybe something is about Runnable?!

+3  A: 

You could absolutely change the interface as you've suggested, but what is the point? What advantage does it bring to provide an instance of MyInterface rather than Runnable? One advantage of Runnable is that it would make it easier to make the code multi-threaded in the future, because most of the APIs that execute threads (e.g. Executor) work with instances of Runnable.

Don
A: 

The point is what about if I want to supply some parameter to myInterface in the future. I mean I cannot extend Runnable with overloaded run method. However, current implementation doesn't use threads, only calls runnable.run().

klaudio
This should be a comment to @Don's answer, not an answer in itself.
Bert F
A: 

Could this change in the future? I think not. In first moment I was not sure will calling run cause separate thread execution, but then I found some hints it wouldn't. That's why I want to avoid unnecessary calling runnable.run

klaudio
@klaudio - Seriously, there is an `add comment` button that should be used for comments and responses to questions. Please click it and it will open up a text box for you to type your responses into. This way your responses are put close to the question you are answering. See there's one down below this comment vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv.
Bert F
sorry, i thought comments allow maximally 15 characters :-)
klaudio
Yeah - a comment! Welcome to SO - we're glad you're here!. Nope, comments *require* at least fifteen characters, but allow up to *600* characters.
Bert F