nerdexam
Oracle

1Z0-819 · Question #156

Given: package a; public abstract class Animal { protected abstract void walk(); } package b; public abstract class Human extends Animal { // line 1 } Which two lines inserted in line 1 will allow…

The correct answer is A. protected void walk(){} E. public abstract void walk(). A works because Human is also abstract, so it can provide a concrete implementation of walk() - and since walk() is protected in Animal, the overriding method must be protected or more visible (not less). E works because an abstract class is allowed to re-declare an abstract…

Java Object-Oriented Approach

Question

Given: package a; public abstract class Animal { protected abstract void walk(); } package b; public abstract class Human extends Animal { // line 1 } Which two lines inserted in line 1 will allow this code to compile? (Choose two.)

Options

  • Aprotected void walk(){}
  • Bvoid walk(){}
  • Cpublic void walk(){}
  • Dprivate void walk(){}
  • Epublic abstract void walk();

How the community answered

(22 responses)
  • A
    77% (17)
  • B
    14% (3)
  • C
    5% (1)
  • D
    5% (1)

Explanation

A works because Human is also abstract, so it can provide a concrete implementation of walk() - and since walk() is protected in Animal, the overriding method must be protected or more visible (not less). E works because an abstract class is allowed to re-declare an abstract method with the same or broader access modifier, effectively forwarding the obligation to a concrete subclass.

B fails because void walk(){} uses package-private access, which is narrower than protected - Java prohibits reducing visibility when overriding. D fails for the same reason: private is even more restrictive and cannot override an inherited method at all. C (public void walk(){}) is actually valid Java, but it is not listed as a correct answer here - re-read the question: the exam specifically asks which two compile, and only A and E are among the intended pair (note: C would also compile in a real JVM, so this may be a flawed question, but within the exam's logic A and E are the expected picks).

Memory tip: Think "you can only open up access, never lock it down" when overriding - a protected parent method can be overridden as protected or public, but never package-private or private. Abstract classes get a free pass to re-declare abstract methods without providing a body.

Topics

#abstract methods#method overriding#access modifiers#inheritance

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice