/home/wpollock1/public_html/Java/Fruit2.java

// Fruit2.java - A demonstration of inheritance showing
// how to "override" inherited methods and polymorphism.
// Note only instance methods may be over-ridden, never
// static methods (nor class or instance variables).
//
// 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) + "." );
   }

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

      // This shows dynamic binding (a.k.a. polymorphism):
      System.out.println( "\n\n  Polymorphism at work:" );
      Fruit f = a;
      f.describe();  // Apple.describe() or Fruit.describe()?
      f = p;
      f.describe();  // Pear.describe() or Fruit.describe()?
   }
}