Table + coffetable + array Learn programming Java



Lesson:

OOP More On Classes


Exercise:

Table + coffetable + array


Objetive:

Create a project named "Tables2", based on the "Tables" project.

In it, create a class "CoffeeTable" that inherits from "Table". Its method "ShowData", besides writing the width and height, must display "(Coffee table)."

Create an array that contains 5 tables and 5 coffee tables. The tables must have random sizes between 50 and 200 cm, and the coffee tables from 40 to 120 cm. Show all their data.


Code:

package Tables2;
import java.util.*;

public class CoffeeTable extends Table
{
	public CoffeeTable(float width, float height)
	{
		this.width = width;
		this.height = height;
	}
	@Override
	public void ShowData()
	{
		System.out.printf("(Coffee table) Width: %1$s, Heigth: %2$s" + "\r\n", width, height);
	}
}

public class Table
{
	protected float width, height;

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

	public final void setWidth(float value)
	{
		width = value;
	}
	public final float getWidth()
	{
		return width;
	}
	public final void setHeight(float value)
	{
		height = value;
	}
	public final float getHeight()
	{
		return height;
	}

	public void ShowData()
	{
		System.out.printf("Width: %1$s, Heigth: %2$s" + "\r\n", width, height);
	}
}

public class Main
{
	public static void main(String[] args)
	{
		boolean debug = false;

		Table[] myTables = new Table[10];
		Random rnd = new Random();

		for (int i = 1; i <= 10; i++)
		{
			if ((i % 2 == 0) && (i != 1))
			{
				myTables[i - 1] = new Table(rnd.nextInt(50, 201), rnd.nextInt(50, 201));
				myTables[i - 1].ShowData();
			}
			else
			{
				myTables[i - 1] = new CoffeeTable(rnd.nextInt(40, 121), rnd.nextInt(40, 121));
				myTables[i - 1].ShowData();
			}

		}

		if (debug)
		{
			new Scanner(System.in).nextLine();
		}
	}
}



Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.