-1

I am not understanding below program.Runnable is an interface and constructor will not be there in any interface.In this program, how new Runnable(){...} is working?

public class Threads {
    public static void main (String[] args) {
        new Thread(new Runnable() {
            public void run() {
                System.out.print("bar");
        }}).start();    
    }
}
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
user2533604
  • 655
  • 1
  • 11
  • 28
  • 4
    You'll want to have a read through [Anonymous Classes](http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html) – MadProgrammer Nov 04 '13 at 05:06
  • check http://stackoverflow.com/questions/4105640/anonymous-class-extending-thread-in-java – upog Nov 04 '13 at 05:10

4 Answers4

2

Firstly, what this program is doing is instantiating a new thread from within your main method that prints text to the console.

Now, the Thread class constructor accepts a class that implements the Runnable interface. We can supply a instance to the Thread constructor two ways. We can use a concrete class that implements Runnable or supply an Anonymous Inner Class. In this case you are doing the later.

According to the Oracle Documentation on Anonymous inner classes. Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.

 new Thread(new Runnable() {
     public void run() {
         System.out.print("bar");
     }
 }).start();

So you can think of this as passing a class of the Runnable interface which satisfies the contract by overriding the run method and defining it within the constructor parameter.

Mario Dennis
  • 2,986
  • 13
  • 35
  • 50
1

It is creating an instance of anonymous class here:

new Runnable() {

and not of interface Runnable

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
1

new Thread() expects a Runnable class. So you are using an anonymous inner class to achieve this. The following is the more verbose way of doing the same thing:

public class Threads {
    public static void main (String[] args) {
        MyRunnable runnable = new MyRunnable();
        Thread thread = new Thread(runnable);
        thread.start();
    }
}

class MyRunnable implements Runnable {
    public void run() {
        System.out.print("bar");
    }
}
Samuel O'Malley
  • 3,471
  • 1
  • 23
  • 41
0

Below code instantiates an anonymous inner class for Thread implemented by Runnable interface by overriding run() method. You can refer to this link for in detail stuff on inner classes.

   new Thread(new Runnable() {
public void run() {
System.out.print("bar");
}}).start();
Dark Knight
  • 8,218
  • 4
  • 39
  • 58