Fruit1.java

Download this source file

// Fruit1.java - A demonstration of inheritance
// Written 1999 Wayne Pollock, Tampa FL USA.

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." );
   }
}


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) + "." );
   }
}


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 Fruit1
{
   public static void main ( String [] args )
   {
      Apple a = new Apple( "red", 0.2 );
      Pear  p = new Pear( "yellow", 0.15 );
      a.describe();
      a.cost();
      p.describe();
      p.cost();
   }
}

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