Challenge: Polymorphism

Write an abstract class and implement abstract methods for child classes using polymorphism.

We'll cover the following

Task

An abstract User class is given below. It commits the classes that inherit from it to calculate the number of scores that a user has depending on the number of articles that they have authored or edited. On the basis of the User class, create the Author and Editor classes. Both classes should calculate the number of scores with the method calcScores(), although the calculated value will differ between the two classes.

  • Add concrete methods to set and get the number of articles:

    1. setNumberOfArticles($int) ($int stands for an integer)
    2. getNumberOfArticles()
  • Add the abstract method calcScores() to calculate the scores separately for each class.

  • Create an Author class that inherits from the User class. For the Author, create a concrete calcScores() method that returns the number of scores from the following calculation:

    numberOfArticles * 10 + 20

  • Also, create an Editor class that inherits from the User class. For the Editor, create a concrete calcScores() method that returns the number of scores from the following calculation:

    numberOfArticles * 6 + 15

  • In the test() method, create an object $author1 from the Author class and set the number of articles to 8. Create another object $editor1 from the Editor class, set the number of articles to 15, and return the scores that the author and editor gained.

Expected output

Author score is 100 and Editor score is 105

Since these problems are designed for your practice, try to solve them yourself first. If you get stuck, you can click the “Show Solution” button to see how the problem can be solved. Good luck!

Coding exercise

Get hands-on with 1400+ tech skills courses.