go to previous page   go to home page   go to next page

Answer:

See below


Full Forest

 
// 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?

  1. area() method of myForest is called
    1. if tree0 is not null, tree0 calls its area() method
      1. which calls area() of its branches, and then
      2. calls area() of its trunk
      3. returns the sum of those areas
    1. if tree1 is not null, tree1 calls its area() method
      1. which calls area() of its branches, and then
      2. calls area() of its trunk
      3. returns the sum of those areas
    1. if tree2 is not null, tree2 calls its area() method
      1. which calls area() of its branches, and then
      2. calls area() of its trunk
      3. returns the sum of those areas
    1. if tree3 is not null, tree3 calls its area() method
      1. which calls area() of its branches, and then
      2. calls area() of its trunk
      3. returns the sum of those areas
  2. All the Tree areas are added up.
  3. The total area is returned to the caller.

Quite a lot of action for one innocent-looking method call !


QUESTION 18:

There are other methods that might be useful. But let's stop here.


go to previous page   go to home page   go to next page