nerdexam
Oracle

1Z0-829 · Question #14

Given: class A { public void mA() {System.out.println("mA");}} class B extends A {public void mB() {System.out.println("mB");}} class C extends B {public void mC() {System.out.println("mC");}}…

The correct answer is E. mA. Option E (mA) is listed as correct, but this answer key contains an error - the program actually prints mB. Since C extends B, the runtime type of cObj (which is C) satisfies instanceof B, making the condition true; the if branch executes and v.mB() prints "mB", never reaching…

Java Object-Oriented Approach

Question

Given: class A { public void mA() {System.out.println("mA");}} class B extends A {public void mB() {System.out.println("mB");}} class C extends B {public void mC() {System.out.println("mC");}} public class App { public static void main(String[] args) { A bObj = new B(); A cObj = new C(); if (cObj instanceof B v) { v.mB(); } else { cObj.mA(); } } } What is the result?

Options

  • AMb
  • BMC
  • CMb
  • DMA
  • EmA

How the community answered

(49 responses)
  • A
    2% (1)
  • B
    2% (1)
  • C
    6% (3)
  • D
    12% (6)
  • E
    78% (38)

Explanation

Option E (mA) is listed as correct, but this answer key contains an error - the program actually prints mB. Since C extends B, the runtime type of cObj (which is C) satisfies instanceof B, making the condition true; the if branch executes and v.mB() prints "mB", never reaching the else branch that would call cObj.mA().

Why each distractor fails:

  • A/C (Mb): These appear to be the same as the real answer ("mB"), suggesting a case-sensitivity formatting error in the choices; the actual output "mB" comes from System.out.println("mB").
  • B (MC/mC): mC() is never called; nothing in the code invokes it.
  • D (MA/mA): This would only print if the instanceof B check were false - but since C is a subtype of B, it is always true, so the else branch is unreachable.

Memory tip: For instanceof with pattern matching, remember the chain: if C extends B, then every C is also a B (and also an A). Always trace the full inheritance chain before evaluating the condition - if the runtime type is a descendant of the tested type, the check passes.

Note to exam takers: Verify the answer key with your instructor - based on Java semantics, the correct output should be "mB", not "mA".

Topics

#Pattern Matching#instanceof#Inheritance#Polymorphism

Community Discussion

No community discussion yet for this question.

Full 1Z0-829 Practice