Exercise: Create a toy class, and a cuddly toy class to inherit it

This exercise is provided to allow potential course delegates to choose the correct Wise Owl Microsoft training course, and may not be reproduced in whole or in part in any format without the prior written consent of Wise Owl.

The answer to the exercise will be included and explained if you attend the Wise Owl course listed below!

Category ==> Visual C Sharp 2010  (65 exercises)
Topic ==> Inheritance  (4 exercises)
Level ==> Average difficulty
Course ==> Adv C# | Classes & LINQ

You need a minimum screen resolution of about 700 pixels width to see our exercises. This is because they contain diagrams and tables which would not be viewable easily on a mobile phone or small laptop. Please use a larger tablet, notebook or desktop computer, or change your screen resolution settings.

The first part of this exercise should make the following code work (help follows!):

// buy a couple of normal toys

Toy t1 = new Toy("Games console", 99.99);

t1.Buy();

 

Toy t2 = new Toy("Lego set", 11.99);

t2.Buy();

 

string s = "";

foreach (Toy t in Toy.Toys)

{  s += t.Description + "\n";  }

MessageBox.Show(s.Trim(),"Purchases");

When you run this code, you should get the following message:

List of toys bought

The code concatenates together the descriptions of all the toys bought.

 

To get this started, create a new Toy class and add into it a static list containing the toys bought:

Creating collection of toys

The start of your toy class.

Add:

  •  a constructor which will take the name and price of a toy, and store these in private fields in the class;
  • a description property, which will return a description of the toy (the name, followed by the price in brackets); and
  • a Buy method which will add the current toy to the Toys list.

Write the code shown at the start of this exercise in a test form, and run it to check that your system works so far.

Now add a CuddlyToy class such that the following code works:

// buy a couple of normal toys

Toy t1 = new Toy("Games console", 99.99);

t1.Buy();

 

Toy t2 = new Toy("Lego set", 11.99);

t2.Buy();

 

// buy a cuddly toy (saying what type it is)

CuddlyToy t3 = new CuddlyToy("Flopsy rabbit", 5.99);

t3.Animal = "Rabbit";

t3.Buy();

 

string s = "";

foreach (Toy t in Toy.Toys)

{

s += t.Description + "\n";

}

MessageBox.Show(s.Trim(),"Purchases");

Your CuddlyToy class should inherit from the Toy class.  You'll need to add a constructor to it which runs the base constructor, add a write-only Animal property and override the Description property in the base class!

Check that when you run your system now, you get a longer list:

List of toys including cuddly toy

The revised list now includes a prefix in upper case for each cuddly toy bought.

 

You've now cracked object-oriented programming!

This page has 0 threads Add post