Bird
0
0

Find the error in this PHP code:

medium📝 Debug Q7 of 15
PHP - Inheritance and Polymorphism
Find the error in this PHP code:
abstract class Fruit {
  abstract protected function color();
}

class Apple extends Fruit {
  public function color() {
    return "Red";
  }
}
AMethod color() visibility must be protected or less in subclass
BNo error, code is correct
CCannot override abstract method color()
DAbstract method color() must be public in subclass
Step-by-Step Solution
Solution:
  1. Step 1: Check abstract method declaration

    Fruit declares abstract protected function color().
  2. Step 2: Check subclass implementation

    Apple implements color() as public, which is allowed.
  3. Step 3: Visibility rules in PHP

    Child class methods can have the same or less restrictive visibility than the parent (public is less restrictive than protected).
  4. Final Answer:

    No error, code is correct -> Option B
  5. Quick Check:

    Child visibility same or wider than parent [OK]
Quick Trick: Child method visibility must be same or less restrictive than parent [OK]
Common Mistakes:
  • Thinking child cannot make method more public
  • Believing visibility must match exactly
  • Assuming public override of protected abstract is invalid

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes