tabla + coffetable + leg Aprende programación con ejercicios Java

Lección:

Más sobre Clases


Ejercicio:

tabla + coffetable + leg 39


Objetivo:

Amplíe el ejemplo de las tablas y las mesas de centro, para agregar una clase "Leg" con un método "ShowData", que escribirá "I am a leg" y luego mostrará los datos de la tabla a la que pertenece.

Elija una tabla en el ejemplo, agréguele una pata y pídale a esa pierna que muestre sus datos.


Código:

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();
	}
}