See below
// Forest.java
//
public class Forest
{
// instance variables
private Tree tree0=null, tree1=null, tree2=null, tree3=null;
// methods
public void setTree( int treeNum, Tree tree ) { ... }
public Tree getTree( int treeNum ) { ... }
public String toString() { ... }
public double area()
{
double area = 0.0;
if ( tree0 != null ) area += tree0.area();
if ( tree1 != null ) area += tree1.area();
if ( tree2 != null ) area += tree2.area();
if ( tree3 != null ) area += tree3.area();
return area;
}
public double volume()
{
double volume = 0.0;
if ( tree0 != null ) volume += tree0.volume();
if ( tree1 != null ) volume += tree1.volume();
if ( tree2 != null ) volume += tree2.volume();
if ( tree3 != null ) volume += tree3.volume();
return volume;
}
}
Here is a brief testing class:
public class ForestAreaTester
{
public static void main( String[] args )
{
Forest myForest = new Forest();
myForest.setTree( 0, new Tree( 1.0, 1.0, 10.0, 8.0, 0, 0, 0 ) );
myForest.setTree( 2, new Tree( 2.0, 1.4, 30.0, 15.0, 1, 2, 3 ) );
System.out.println( "Total Area = " + myForest.area() );
System.out.println( "Total Volume = " + myForest.volume() );
}
}
What happens when the area() method of myForest is called?
area() method of myForest is called
tree0 is not null, tree0 calls its area() method
area() of its branches, and thenarea() of its trunktree1 is not null, tree1 calls its area() method
area() of its branches, and thenarea() of its trunktree2 is not null, tree2 calls its area() method
area() of its branches, and thenarea() of its trunktree3 is not null, tree3 calls its area() method
area() of its branches, and thenarea() of its trunkQuite a lot of action for one innocent-looking method call !
There are other methods that might be useful. But let's stop here.