Multiple choice technology programming languages

What is the output for the below code ? public class A { public void printValue(){ System.out.println("A"); } } public class B extends A { public void printValue(){ System.out.println("B"); } } 1. public class Test { 2. public static void main(String... args) { 3. A b = new B(); 4. newValue(b); 5. } 6. public static void newValue(A a){ 7. if(a instanceof B){ 8. ((B)a).printValue(); 9. } 10. } 11.}

  1. A

  2. Compilation fails with an error at line 4

  3. B

  4. Compilation fails with an error at line 8

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

This demonstrates Java polymorphism and instanceof operator. A b = new B() creates a B object but assigns it to A reference. The instanceof check (a instanceof B) returns true because the actual object is B. The cast ((B)a) is safe, and B's printValue() method executes, printing 'B'. This is runtime polymorphism in action.

AI explanation

To answer this question, let's go through each line of code to understand what it does:

  1. The Test class is defined.
  2. The main method is defined with the parameter "args" of type String array.
  3. An object "b" is created of type A, but it refers to an instance of class B. This is possible because class B is a subclass of class A.
  4. The "newValue" method is called with the object "b" as an argument.
  5. The main method ends.
  6. The "newValue" method is defined with a parameter "a" of type A.
  7. The "instanceof" operator is used to check if the object "a" is an instance of class B.
  8. If the condition in line 7 is true, the printValue method is called on the object "a" after casting it to type B.
  9. The method ends.
  10. The Test class ends.

Since the object "b" is an instance of class B, the condition in line 7 is true. Therefore, the printValue method of class B is called in line 8, which prints "B" to the console. Hence, the output of the code is:

C) B