Fruit3.java

Download this source file

// Fruit3.java - A demonstration of inheritance showing
// abstract classes and methods.
//
// 1999 Wayne Pollock, Tampa FL USA.

/*abstract*/ class Fruit
{
   String color;
   double weight;

   public Fruit ( String c, double w )  // Fruit constructor
   {
      color = c;
      weight = w;
   }

   public void describe ()
   {
      System.out.println( "I am " + color +
         " and I weigh " + weight + " pounds." );
   }

//   abstract public void cost () ; // All derived class must provide
                                  // a cost method!
}


class Apple extends Fruit
{
   public Apple ( String color, double weight )
   {
      super( color, weight );
   }

   public void cost ()
   {
      System.out.println( "I'm an Apple that costs $" +
                          (0.30 * weight) + "." );
   }

   public void describe ()  // Overrides "Fruit.describe()"!
   {
      System.out.println( "I am a " + color + " apple, " +
         " and I weigh " + weight + " pounds." );
   }
}


class Pear extends Fruit
{
   public Pear ( String color, double weight )
   {
      super( color, weight );
   }

   public void cost ()
   {
      System.out.println( "I'm a Pear that costs $" +
                          (0.25 * weight) + "." );
   }
}


public class Fruit3
{
   public static void main ( String [] args )
   {
      Fruit f;
      f = new Fruit( "green", 0.1 );
      f.describe();

      f = new Apple( "red", 0.2 );
      f.describe();
   }
}

Send comments and questions to pollock@acm.org.
Valid HTML 4.01!   Valid CSS!   CAST: Bobby WorldWide Approved 508   CAST: Bobby WorldWide Approved AAA