Reputation: 3471
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?
Upvotes: 0
Views: 58
Reputation: 965
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()
Upvotes: 1