Following code will result in: class A { public static void main(String [] args) {B b = new A(); }} class B extends A {}

  1. Compile error

  2. Runtime Exception

  3. No error


Correct Option: A

AI Explanation

To answer this question, we need to understand the concept of inheritance and object creation in Java.

In the given code, we have two classes: A and B. Class A has a main method, which is the entry point of the program. Inside the main method, a new object b is created of type B using the constructor new A().

Now let's go through each option to understand why it is correct or incorrect:

Option A) Compile error - This option is correct. The code will result in a compile error because we are trying to create an object of type B using the constructor of class A. Since class B extends class A, it is valid to create an object of type B using the constructor of class B, but not vice versa. Therefore, the code B b = new A(); will result in a compile error.

Option B) Runtime Exception - This option is incorrect. There will be no runtime exception because the code will not compile in the first place.

Option C) No error - This option is incorrect. There will be a compile error, as explained in option A.

The correct answer is A) Compile error. This option is correct because we are trying to create an object of type B using the constructor of class A, which is not allowed in Java.

Find more quizzes: