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
πŸ’¬ Discuss
βœ… Correct Answer: (B) B
Explanation: 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.
Explanation by: Praveen Singh
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.

πŸ’¬ Discussion


πŸ“Š Question Analytics

πŸ‘οΈ
204
Total Visits
πŸ“½οΈ
1 y ago
Published
πŸŽ–οΈ
Praveen Singh
Publisher
πŸ“ˆ
84%
Success Rate