Paras Paras - 5 months ago 13
Android Question

Understanding Runnable in Android

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?

Answer

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()
Comments