All the posts and topics that contain only an error report will be moved here after the error is corrected. This is to ensure that when users view a question in ETS Viewer, the "Discuss" button will not indicate the presence of a discussion that adds no value to the question.
Since b is declared of a type that indirectly implements Runnable, the compiler can figure out that b will always point to an object that is assignable to a Runnable. Therefore, explicit cast is not required here. It is will still work fine with the explicit cast though.
But if I try to avoid the explicit cast on NetBeans i get:
incompatible types: Object cannot be converted to Runnable
Option 5 and the explanation are correct. You need to post the exact code that you have typed. There must be some difference because of which you are getting this message.
BTW, try to use command line to compile and run code while preparing for the exam. We do not recommend using IDEs for this purpose.
If you like our products and services, please help us by posting your review here.
The compiler doesn't know because Object is superclass for all class? So Runnable is a Object not unlike, (Object o) though now being a reference for (a) the compiler does not check the actual reference variable, only the type declared on (Object o) ?
Yes, that is correct. Since the compiler doesn't execute any code it can only see if it is possible for a variable to point to an object to which it is being cast. If there is a possibility, it allows the cast, otherwise, it generates an error. For example,
String s = "some string";
Runnable r = (String) s; <-- this will not compile because the compiler knows that s can never point to an object that is-a Runnable.
HTH,
Paul.
If you like our products and services, please help us by posting your review here.
Option 1 and option 4 both are trying to assign o to a reference of a different type. The declared class of o is Object while the declared type of the target is Runnable or Observable. Both are wrong for the same reason as explained in the explanation, "Although o refers to an object which is Runnable but the compiler doesn't know about it. You have to do: Runnable r = (Runnable) o;"
HTH,
Paul.
If you like our products and services, please help us by posting your review here.