PracticeAbstract classes and methods

Practice: Abstract classes and methods

In the "Abstract classes and methods" tutorial, we learned about abstract methods that we use in order to commit the child classes to supply concrete methods.

In the following exercise, we will have a chance to practice everything that we have learned in the tutorial by writing our own code.

Coding exercise

In the following example, we will create an abstract User class and two child classes (Admin and Viewer classes) that inherit from the abstract class.

Create an abstract class with the name of User, which has an abstract method with the name of stateYourRole().

Solution:

Scratchpad to practice your coding *This will not be saved nor submitted to us.*

<?php
//Your practice code

Add to the class a protected variable with the name of $username, and public setter and getter methods to set and get the $username.

Solution:

Scratchpad to practice your coding *This will not be saved nor submitted to us.*

<?php
//Your practice code

Create an Admin class that inherits the abstract User class.

Solution:

Scratchpad to practice your coding *This will not be saved nor submitted to us.*

<?php
//Your practice code

Which method should be defined in the class?

Solution:

Scratchpad to practice your coding *This will not be saved nor submitted to us.*

<?php
//Your practice code

Define the method stateYourRole() in the child class and let it return the string "admin";

Solution:

Scratchpad to practice your coding *This will not be saved nor submitted to us.*

<?php
//Your practice code

Create another class, Viewer that inherits the User abstract class. Define the method that should be defined in each child class of the User class.

Solution:

Scratchpad to practice your coding *This will not be saved nor submitted to us.*

<?php
//Your practice code

Create an object from the Admin class, set the username to "Balthazar", and make it return the string "admin".

Expected result:
admin

Solution:

Scratchpad to practice your coding *This will not be saved nor submitted to us.*

<?php
//Your practice code
comments powered by Disqus