Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Runnable Question

I'm currently taking a course in Java and I've run into some confusing code.

Example:

Runnable runnable = new Runnable()
        {
            public void run()
            {
                //doStuff
            }
        };

I don't really get what this code is doing.

How can the run method be associated with an instance of a class?

I googled "Runnable" and found out that it is an interface. Am I implementing the interface by declaring the run method between curly brackets ? Can this be done for any interface in java ?

I could use some links/explanations. Thank you!

like image 966
user523228 Avatar asked Nov 28 '10 22:11

user523228


2 Answers

It's an anonymous inner class that's implementing the interface Runnable. Yes, you can implement any interface this way, although there are reasons why you would or wouldn't in any given case (lack of reusability being a big one in the "wouldn't" column). More about anonymous classes here, but it's basically a convenient form of this:

// Define it
class Foo implements Runnable
{
    public void run()
    {
        // Do stuff
    }
}

// And then use it
Runnable runnable = new Foo();

...provided Foo is an inner (or "nested") class. More about nested classes here.

like image 64
T.J. Crowder Avatar answered Sep 19 '22 21:09

T.J. Crowder


yes, you are implementing the interface by declaring the run. Yes it can be done for any interface.

This is typically done when you pass an implementation to a method that expects an argument of an Interface type, and you don't have a declared class that is appropriate. You can just implement the interface on the spot, and that code runs. Pretty neat.

like image 37
hvgotcodes Avatar answered Sep 17 '22 21:09

hvgotcodes