0

I was going through Handlers, the post method in it accepts a parameter of type Runnable. There's a following code snippet I came across

final Handler handler = new Handler();
    handler.post(new Runnable() {
        @Override
        public void run() {
            timeView.clearComposingText();
            Integer hours = seconds/3600;
            Integer minutes = (seconds % 3600)/60;
            Integer secs = seconds % 60;
            String time = String.format("%d:%02d:%02d",hours,minutes,secs);
            timeView.setText(time);

            if(running)
            {
                seconds++;
            }

            handler.postDelayed(this,1000);
        }
    });

Now since Runnable is an Interface in Java, how are we able to create a new instance of Runnable directly?

Paras
  • 3,191
  • 6
  • 41
  • 77
  • This is called an "anonymous inner class." The implementation of the Runnable interface is inlined rather than declaring a class elsewhere. – Karakuri Jun 12 '16 at 06:12
  • 1
    See [“implements Runnable” vs. “extends Thread”](http://stackoverflow.com/questions/541487/implements-runnable-vs-extends-thread) – mjn Jun 12 '16 at 06:13

1 Answers1

1

Anonymous classes can implement interfaces, and that's the only time you'll see a class implementing an interface without the "implements" keyword.

A complete example might look like:

public class MyClass {

  public interface A {
    void foo();
  }

  public interface B {
    void bar();
  }

  public interface C extends A, B {
    void baz();
  }

  public void doIt(C c) {
    c.foo();
    c.bar();
    c.baz();
  }

  public static void main(String[] args) {
    MyClass mc = new MyClass();

    mc.doIt(new C() {
      @Override
      public void foo() {
        System.out.println("foo()");
      }

      @Override
      public void bar() {
        System.out.println("bar()");
      }

      @Override
      public void baz() {
        System.out.println("baz()");
      }
    });
  }

}

The output of this example is:

foo()
bar()
baz()
Abdullah
  • 935
  • 9
  • 18