Fruit2.java
Download Fruit2.java
1: // Fruit2.java - A demonstration of inheritance showing
2: // how to "override" inherited methods and polymorphism.
3: // Note only instance methods may be over-ridden, never
4: // static methods (nor class or instance variables).
5: //
6: // Written 1999 Wayne Pollock, Tampa FL USA.
7:
8: class Fruit
9: {
10: String color;
11: double weight;
12:
13: public Fruit ( String c, double w ) // Fruit constructor
14: {
15: color = c;
16: weight = w;
17: }
18:
19: public void describe ()
20: {
21: System.out.println( "I am " + color +
22: " and I weigh " + weight + " pounds." );
23: }
24: }
25:
26:
27: class Apple extends Fruit
28: {
29: public Apple ( String color, double weight )
30: {
31: super( color, weight );
32: }
33:
34: public void cost ()
35: {
36: System.out.println( "I'm an Apple that costs $" +
37: (0.30 * weight) + "." );
38: }
39:
40: public void describe () // Overrides "Fruit.describe()"!
41: {
42: System.out.println( "I am a " + color + " apple, " +
43: " and I weigh " + weight + " pounds." );
44: }
45: }
46:
47:
48: class Pear extends Fruit
49: {
50: public Pear ( String color, double weight )
51: {
52: super( color, weight );
53: }
54:
55: public void cost ()
56: {
57: System.out.println( "I'm a Pear that costs $" +
58: (0.25 * weight) + "." );
59: }
60: }
61:
62:
63: public class Fruit2
64: {
65: public static void main ( String [] args )
66: {
67: Apple a = new Apple( "red", 0.2 );
68: Pear p = new Pear( "yellow", 0.15 );
69: a.describe();
70: p.describe();
71:
72: // This shows dynamic binding (a.k.a. polymorphism):
73: System.out.println( "\n\n Polymorphism at work:" );
74: Fruit f = a;
75: f.describe(); // Apple.describe() or Fruit.describe()?
76: f = p;
77: f.describe(); // Pear.describe() or Fruit.describe()?
78: }
79: }