BuiltWithNOF
Test Prep

Suppose you want to keep track of Xmas trees. All trees have a species and a price. Real trees have a date cut and a height. Artificial trees have the manufacturer’s name. You do not want to change the price of a tree outside of the class. You will need to read the price of this tree outside the class. Write 3 classes including constructors and (only) needed get/set methods.

abstract class Trees
{
private float price; // could be Double
String species;

public Trees (String s, float p)
{
species = s;
price = p;
}

public float getPrice()
{
return price;
}

}

class Artificial extends Trees
{
String name;

public Artificial ( String a, float b, String n)
{
super(a,b);
name = n;
}
}

class Real extends Trees
{
String date;
int height;

public Real (String a, float b, String d, int h)
{
super(a,b);
date = d;
height = h;
}
}

How would you make an array of 40 Real trees in the Driver class? 2 lines: define it and make it.

1. Real r[];

2. r = new Real[40];

Show how you would call the constructor to make a now Real tree with species Fir, price 12.75, Nov 11 cut date, and height of 6.

r[6] = new Real(Fir”,12.75,”Nov 11”,6);

Suppose you have a filled array of Real trees up to a counter called rtcount. Write a Java method to find the most expensive tree, and change this tree’s cut date to the same date as the tree with the biggest height.

(one of many solutions..)

static void FindMethod()
{

String g,d; float p; highP=0.0; int h, highPpos,highH, highHpos = 0;

for (int 1=0; i<rtcount; i++)
{
p = r[i].getPrice();
h = r[i].height;

if (p > highP)
{
highP = p;
highPpos = i; //remember where the most expensive one was
}

if (h > highH)
{
HighH = h;
highHpos = i;
}

d = r[highPpos].date;
r[highPpos].date = d;

}

}

 

[Home] [Syllabus] [Sessions]