OOP Exercise - Implementing Missing Code in Chicken Egg Bird Class Interface Problem Using PHP
This a classic OOP (Object Oriented Programming) problem for interview and coding challenge where you will be given a bird interface to implement and egg class to be completed. Here's how I solved it using PHP
Chicken Egg Problem
Add the missing code to Chicken and Egg so the following actoins are completed:
- Chicken implements the Bird interface.
- A Chicken lays an egg that will hatch into a new Chicken.
- Eggs from other types of birds should hatch into a new bird of their parent type.
- Hatching an egg for the second time throws an Exception
Check problem.php for code template
Output For The Solution.php
The eggOne from chickenOne hatched & new chickenTwo has borned The eggTwo from chickenTwo hatched & new chickenThree has borned Hatching again will cause an exception PHP Fatal error: Uncaught Exception: The egg already hatched in /Users/myusername/code/chicken_egg.php:30 Stack trace: #0 /Users/myusername/code/chicken_egg.php(52): Egg->hatch() #1 {main} thrown in /Users/myusername/code/chicken_egg.php on line 30 Fatal error: Uncaught Exception: The egg already hatched in /Users/myusername/code/chicken_egg.php:30 Stack trace: #0 /Users/myusername/code/chicken_egg.php(52): Egg->hatch() #1 {main} thrown in /Users/myusername/code/chicken_egg.php on line 30
Comments
Leave a comment
You are not LoggedIn but you can comment as an anonymous user which requires manual approval. For better experience please Login .