Exercise
Table + coffetable + leg
Objetive
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.
Example Code
package Tables;
public class CoffeeTable extends Table
{
public CoffeeTable(int tableWidth, int tableHeight)
{
super(tableWidth, tableHeight);
}
@Override
public void ShowData()
{
System.out.printf("Width: %1$s, Height: %2$s" + "\r\n", width, height);
System.out.println("(Coffee table)");
}
}
package Tables;
public class Leg
{
private Table myTable;
public Leg()
{
}
public final void SetTable(Table t)
{
myTable = t;
}
public final void ShowData()
{
System.out.println("I am a leg");
myTable.ShowData();
}
}
package Tables;
public class Table
{
protected int width, height;
protected Leg myLeg;
public Table(int tableWidth, int tableHeight)
{
width = tableWidth;
height = tableHeight;
}
public final void AddLeg(Leg l)
{
myLeg = l;
myLeg.SetTable(this);
}
public void ShowData()
{
System.out.printf("Width: %1$s, Height: %2$s" + "\r\n", width, height);
}
}
package Tables;
import java.util.*;
public class TestTable
{
public static void main(String[] args)
{
// Using as a single table:
Table t = new Table(80, 120);
Leg l = new Leg();
t.AddLeg(l);
l.ShowData();
System.out.println();
// Using as array:
Table[] tableList = new Table[10];
Random random = new Random();
for (int i = 0; i < tableList.length; i++)
{
if (i < tableList.length / 2)
{
tableList[i] = new Table(random.nextInt(50, 201), random.nextInt(50, 201));
}
else
{
tableList[i] = new CoffeeTable(random.nextInt(40, 121), random.nextInt(40, 121));
}
}
for (int i = 0; i < tableList.length; i++)
{
tableList[i].ShowData();
}
// TODO: To be removed
new Scanner(System.in).nextLine();
}
}