nerdexam
Oracle

1Z0-803 · Question #122

Given: abstract class A1 { public abstract void m1(); public void m2() { System.out.println("Green"); } } abstract class A2 extends A1 { public abstract void m3(); public void m1() { System.out.printl

The correct answer is A. Yellow. The code demonstrates Java polymorphism and method overriding where an A3 object is referenced by an A2 type variable, causing method calls to resolve to the A3 class's overridden implementations.

Working with Inheritance

Question

Given:

abstract class A1 { public abstract void m1(); public void m2() { System.out.println("Green"); } } abstract class A2 extends A1 { public abstract void m3(); public void m1() { System.out.println("Cyan"); } public void m2() { System.out.println("Blue"); } } public class A3 extends A2 { public void m1() { System.out.println("Yellow"); } public void m2() { System.out.println("Pink"); } public void m3() { System.out.println("Red"); } public static void main (String[] args) { A2 tp = new A3(); tp.m1(); tp.m2(); tp.m3(); } } What is the result?

Options

  • AYellow
  • BCyan
  • CCyan
  • DCompilation fails

How the community answered

(28 responses)
  • A
    68% (19)
  • B
    11% (3)
  • C
    4% (1)
  • D
    18% (5)

Why each option

The code demonstrates Java polymorphism and method overriding where an `A3` object is referenced by an `A2` type variable, causing method calls to resolve to the `A3` class's overridden implementations.

AYellowCorrect

When `A2 tp = new A3();` is executed, an instance of `A3` is created and assigned to a reference variable of type `A2`. Due to polymorphism, calling `tp.m1()` will invoke the `m1()` method of the actual object type, which is `A3`, thus printing "Yellow".

BCyan

"Cyan" would be printed if `tp` were an instance of `A2` or if `A3` did not override `m1()`, allowing `A2`'s implementation to be called.

CCyan

This choice is identical to B and would only be correct if `A2.m1()` was invoked.

DCompilation fails

The code compiles successfully because all abstract methods are implemented, and the type assignment is valid due to inheritance and polymorphism.

Concept tested: Java polymorphism, method overriding, abstract classes

Source: https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html

Topics

#inheritance#abstract classes#method overriding#polymorphism

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice