5

我目前正在学习 Java 课程,但遇到了一些令人困惑的代码。

例子:

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

我真的不明白这段代码在做什么。

run 方法如何与类的实例相关联?

我用谷歌搜索了“Runnable”,发现它是一个界面。我是否通过在大括号之间声明 run 方法来实现接口?这可以为java中的任何接口完成吗?

我可以使用一些链接/解释。谢谢!

4

4 回答 4

8

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.

于 2010-11-28T22:23:51.863 回答
2

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.

于 2010-11-28T22:24:19.927 回答
2

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 ?

Yes!

This code is instantiating an object which implements Runnable. Because we can't actually construct an interface, any code which attempts to do so must provide implementations for the interface's methods in curly brackets. We don't really get to see what class Java is creating to implement Runnable (these are abstract terms).

If you were to do the following:

Runnable runnable = new Runnable()
        {
            public void run()
            {
                System.out.println("I'm running");
            }
        };
runnable.run();

you would see "I'm running" as your output.

于 2010-11-28T22:28:08.557 回答
0

在某些情况下,此示例代码将很有用....test runna = new test()

class test implements Runnable{
        test(){
            Thread t = new Thread(this);
            t.start();
        }
        @Override
        public void run() {
            // TODO Auto-generated method stub
            while(true){
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.print("asd");
            }
        }

    }
于 2010-12-25T14:55:38.270 回答