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

Answer:

No. Ordinarily you want to use the minimum number of instance variables that describe the object.


Inconsistencies

If a quantity can be calculated from existing instance variables it is best to provide a method that does the calculation and use it when needed. Examine the following code:


 
// file: Cone.java
//
public class Cone
{
  private double radius;  // radius of the base
  private double height;  // height of the cone
  private double area;    // area of the cone
  private double volume;  // volume of the cone
  
  public Cone( double radius, double height )
  {
    this.radius = radius;
    this.height = height;
    this.area = Math.PI*radius*(radius + Math.sqrt(height*height + radius*radius) );
    this.volume = Math.PI*radius*radius*height/3.0;
  }
  
  public double area()
  {
    return area;
  }
  
  public double volume()
  {
    return volume;
  }
  
  public void setHeight( double height )
  {
    if ( height >= 0 )
      this.height = height ;
  }
  
  public void setRadius( double radius )
  {
    if ( radius >= 0 )
      this.radius = radius ;
  }
  
  public double getHeight( )
  {
    return height ;
  }
  
  public double getRadius( )
  {
    return radius ;
  }
  
}


QUESTION 24:

Is anything wrong with this code?


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