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…
Question
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)- A12% (6)
- B4% (2)
- C62% (32)
- E23% (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
publicwidens the parent'srevolve(), but n3 still declares it with default access, so the override still narrows visibility. The error remains. - B - Making n2
publicchangesabstract void rotate()topublic abstract void rotate(). Nowprotected 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 itpublicchanges 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
Community Discussion
No community discussion yet for this question.