What is the output for the following lines of code? 1: class Test 2: { 3: static void show() 4: { 5: System.out.println("Static method in Test"); 6: } 7: } 8: public class Q4 extends Test 9: { 10: void show() 11: { 12: System.out.println("Overridden static method in Q4"); 13: } 14: public static void main(String[] args) 15: { 16: } 17: }

  1. Compilation error at line 3.

  2. Compilation error at line 10.

  3. No compilation error, but runtime exception at line 3.

  4. No compilation error, but runtime exception at line 10.


Correct Option: B

AI Explanation

To answer this question, we need to understand the concept of method overriding in Java.

In the given code, we have a class Test with a static method show() defined at line 3. The show() method simply prints "Static method in Test" to the console.

Then, we have another class Q4 which extends the Test class. In the Q4 class, we have a method show() defined at line 10. This method is an instance method and it also prints a message to the console: "Overridden static method in Q4".

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

Option A) Compilation error at line 3 - This option is incorrect. There is no compilation error at line 3. The show() method in the Test class is a static method, and it can be called using the class name.

Option B) Compilation error at line 10 - This option is correct. The show() method in the Q4 class is an instance method and it is trying to override the static method show() in the Test class. However, it is not possible to override a static method with an instance method. Therefore, a compilation error will occur at line 10.

Option C) No compilation error, but runtime exception at line 3 - This option is incorrect. There is no runtime exception at line 3. The show() method in the Test class is a valid static method.

Option D) No compilation error, but runtime exception at line 10 - This option is incorrect. There is no runtime exception at line 10. The compilation error at line 10 prevents the code from executing, so there won't be any runtime exception.

The correct answer is B. There is a compilation error at line 10 because it is not possible to override a static method with an instance method in Java.

Find more quizzes: