nerdexam
Oracle

1Z0-808 · Question #41

Given the code fragment: ``java abstract class Planet { protected void revolve() { //line n1 } } abstract void rotate(); class Earth extends Planet { void revolve() { //line n3 } } protected void…

The correct answer is C. Make the method at line n3 public. D. Make the method at line n3 protected. Options C and D both fix the single root cause: Earth.revolve() at line n3 uses default (package-private) access, which reduces the visibility inherited from Planet.revolve() (which is protected). Java prohibits narrowing access when overriding - you must match or widen it…

Working with Inheritance

Question

Given the code fragment:
abstract class Planet {
 protected void revolve() { //line n1
 }
}

abstract void rotate();

class Earth extends Planet {
 void revolve() { //line n3
 }
}

protected void rotate() { //line n4
}
Which two modifications made independently, enable the code to compile?

Options

  • AMake the method at line n1 public.
  • BMake the method at line n2 public.
  • CMake the method at line n3 public.
  • DMake the method at line n3 protected.
  • EMake the method at line n4 public.

How the community answered

(52 responses)
  • A
    12% (6)
  • B
    4% (2)
  • C
    62% (32)
  • E
    23% (12)

Explanation

Options C and D both fix the single root cause: Earth.revolve() at line n3 uses default (package-private) access, which reduces the visibility inherited from Planet.revolve() (which is protected). Java prohibits narrowing access when overriding - you must match or widen it. Making n3 protected (D) matches the parent exactly; making it public (C) widens it - both are legal.

Why the distractors fail:

  • A - Making n1 public widens the parent's revolve(), but n3 still declares it with default access, so the override still narrows visibility. The error remains.
  • B - Making n2 public changes abstract void rotate() to public abstract void rotate(). Now protected void rotate() at n4 would narrow access from public to protected, introducing a new compilation error.
  • E - The protected void rotate() at n4 already legally widens access relative to n2's default-access abstract method. Making it public changes nothing meaningful and doesn't fix the actual error at n3.

Memory tip: Think of access modifiers as a one-way ratchet when overriding - you can only turn it toward more open (private → default → protected → public), never back. If the parent is protected, the child must be protected or public.

Topics

#access modifiers#method overriding#abstract methods#inheritance

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice