How is the below structure possibly working? Please explain.
Thanks in advance.
public abstract class AbstractCallableClass {
protected abstract V getCallable();
public void passRunnable() {
runnableParamterised(this.getCallable());
}
public void runnableParamterised(Runnable runnable) {
System.out.println(runnable.toString());
}
}
class OneCallableClass implements Callable {
@Override
public Object call() throws Exception {
return "Any dummy response";
}
}
class TestClass extends AbstractCallableClass {
@Override
protected V getCallable() {
return new OneCallableClass();
}
}
It's not working as it is mentioned in the above sample. But apparently, the Callable is getting typecast-ed as Runnable when passed as an argument and is working in production.
You can't cast
Callableto aRunnable- it will lead toClassCastException, unless the callable is also a runnable (imagine a class implementing both interfaces).You can implement a simple adapter to wrap a callable and pass it as a runnable, where one is required:
Usage: