Multiple choice technology architecture

What will happen if you attempt to compile and run the following code? class Base {} class Sub extends Base {} class Sub2 extends Base {} public class CEx{ public static void main(String argv[]){ Base b=new Base(); Sub s=(Sub) b; } }

  1. Compile and run without error

  2. Compile time Exception

  3. Runtime Exception

  4. None of the above

Reveal answer Fill a bubble to check yourself
C Correct answer
Explanation

Code compiles successfully since Base to Sub cast is syntactically valid. At runtime, b is a Base object, not a Sub. Downcasting requires the actual object type to match, so this throws ClassCastException.

AI explanation

To answer this question, let's go through each option to understand why it is correct or incorrect:

Option A) Compile and run without error - This option is incorrect because the code will not compile successfully due to a type casting error. Option B) Compile time Exception - This option is incorrect because the code will not throw a compile-time exception. Option C) Runtime Exception - This option is correct because the code will throw a runtime exception due to the incorrect type casting of the object 'b' to the subclass 'Sub'. Option D) None of the above - This option is incorrect because option C is the correct answer.

The correct answer is C. This option is correct because the code will throw a runtime exception due to the incorrect type casting of the object 'b' to the subclass 'Sub'.