Wednesday, July 25, 2007

Programming Exercise (Ungraded): Inheritance

Implement the following class hierarchy:


Description of each class and its members:
  • Phone - an abstract class
    • Type - an abstract readonly property that identifies the type of phone. Implemented by subclasses
    • Number - an abstract property that sets and gets the phone number. Implemented by subclasses
    • Ring - an abstract method that will output the message "Ringing phone-type" when invoked. Implemented by subclasses
  • Telephone - an implementation of the Phone abstract class that represents all landline-based phones
    • Telephone - constructor that accepts a phone number as parameter
    • Type - returns "Telephone"
    • Number - gets or sets the phone number. This property should also validate the assigned phone number using this format: nnn-nnnn
    • Ring - displays the message "Ringing Telephone" when invoked
  • CellularPhone - an implementation of the Phone abstract class that represents all mobile-based phones
    • CellularPhone - constructor that accepts a phone number parameter
    • Type - returns "CellularPhone"
    • Number - gets or sets the phone number. This property should also validate the assigned phone number using this format: nnnn-nnnnnnn
    • Ring - displays the message "Ringing CellularPhone" when invoked
After implementing, you should be able to use your classes as follows:

class Program
{
static void Main(string[] args)
{
Telephone telephone = new Telephone("233-1234");
CellularPhone cellphone = new CellularPhone("0920-1234567");

Console.WriteLine(telephone.Type); // displays "Telephone"
Console.WriteLine(cellphone.Type); // displays "CellularPhone"

telephone.Number = "233-123"; // displays error
Console.WriteLine(telephone.Number); // displays "233-1234"
cellphone.Number = "0920-123x567"; // displays error
Console.WriteLine(cellphone.Number); // displays
"0920-1234567"
Phone phone = cellphone;
Console.WriteLine(phone.Number); // displays
// "0920-1234567"

phone = telephone;
phone.Ring(); // displays "Ringing Telephone"

Console.ReadLine();
}
}