Fruit3.java

Download Fruit3.java

 1: // Fruit3.java - A demonstration of inheritance showing
 2: // abstract classes and methods.
 3: //
 4: // 1999 Wayne Pollock, Tampa FL USA.
 5: 
 6: /*abstract*/ class Fruit
 7: {
 8:    String color;
 9:    double weight;
10: 
11:    public Fruit ( String c, double w )  // Fruit constructor
12:    {
13:       color = c;
14:       weight = w;
15:    }
16: 
17:    public void describe ()
18:    {
19:       System.out.println( "I am " + color +
20:          " and I weigh " + weight + " pounds." );
21:    }
22: 
23: //   abstract public void cost () ; // All derived class must provide
24:                                   // a cost method!
25: }
26: 
27: 
28: class Apple extends Fruit
29: {
30:    public Apple ( String color, double weight )
31:    {
32:       super( color, weight );
33:    }
34: 
35:    public void cost ()
36:    {
37:       System.out.println( "I'm an Apple that costs $" +
38:                           (0.30 * weight) + "." );
39:    }
40: 
41:    public void describe ()  // Overrides "Fruit.describe()"!
42:    {
43:       System.out.println( "I am a " + color + " apple, " +
44:          " and I weigh " + weight + " pounds." );
45:    }
46: }
47: 
48: 
49: class Pear extends Fruit
50: {
51:    public Pear ( String color, double weight )
52:    {
53:       super( color, weight );
54:    }
55: 
56:    public void cost ()
57:    {
58:       System.out.println( "I'm a Pear that costs $" +
59:                           (0.25 * weight) + "." );
60:    }
61: }
62: 
63: 
64: public class Fruit3
65: {
66:    public static void main ( String [] args )
67:    {
68:       Fruit f;
69:       f = new Fruit( "green", 0.1 );
70:       f.describe();
71: 
72:       f = new Apple( "red", 0.2 );
73:       f.describe();
74:    }
75: }