Vidyalelo
Java Programming · Q41

Operators

Programming · Java Programming · question 41

Q41

What will be the output for the below code? class A public void printValue() System.out.println("A"); class B extends A public void printValue() System.out.println("B"); public class Test public static void main(String... args) A b = new B(); newValue(b); public static void newValue(A a) if(a instanceof B) ((B)a).printValue();

A.
A
B.
B
Answer
C.
Compilation fails with an error at line 4
D.
Compilation fails with an error at line 8
E.
None of these

Answer: Option B

Solution

Answer: Option B
Solution:

Instanceof operator is used for object reference variables to check whether an object is of a particular type. In newValue(b); b is instance of B so it works properly.