A

Admin • 802.91K Points
Coach

Q. What will be the output for the below code?

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
  • (C) Compilation fails with an error at line 4
  • (D) Compilation fails with an error at line 4D.Compilation fails with an error at line 8
  • Correct Answer - Option(B)
  • Views: 4
  • Filed under category Java
  • Hashtags:

Explanation by: Admin
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.

You must be Logged in to update hint/solution

Discusssion

Login to discuss.

Be the first to start discuss.