Programming Course in C# ¡Free!

Table + coffetable + leg

 Saturday, April 06, 2013 published by Exercises C#
Proposed exercise

Extend the example of the tables and the coffee tables, to add a class "Leg" with a method "ShowData", which will write "I am a leg" and then it will display the data of the table to which it belongs.

Choose one table in the example, add a leg to it and ask that leg to display its data.

Output



Solution


using System;
class Table
{
protected int width, height;
protected Leg myLeg;

public Table(int width, int height)
{
this.width = width;
this.height = height;
}

public void AddLeg(Leg l)
{
myLeg = l;
myLeg.SetTable(this);
}

public virtual void ShowData()
{
Console.WriteLine("Width: {0}, Height: {1}", width, height);
}
}

class Leg
{ 
Table table;

public Leg()
{

}

public void SetTable(Table t)
{
table = t;
}

public void ShowData()
{
Console.WriteLine("I am a leg");
table.ShowData();
}
}

class CoffeeTable : Table
{
public CoffeeTable(int width, int height) : base (width, height)
{

}

public override void ShowData()
{
Console.WriteLine("Width: {0}, Height: {1}", width, height);
Console.WriteLine("(Coffee table)");
}
}

class TestTable
{
static void Main()
{                
Table t = new Table(80,120);
Leg l = new Leg();

t.AddLeg(l);
l.ShowData();

Table[] tables = new Table[10];
Random r = new Random();

for (int i = 0; i < tables.Length ;i++)
{
if (i < tables.Length / 2)
tables[i] = new Table( r.Next(50, 201), r.Next(50, 201));
else
tables[i] = new CoffeeTable( r.Next(40, 121), r.Next(40, 121));
}

for (int i = 0; i < tables.Length; i++)
tables[i].ShowData();
}
}