Fruit1.java
Download Fruit1.java
1: // Fruit1.java - A demonstration of inheritance
2: // Written 1999 Wayne Pollock, Tampa FL USA.
3:
4: class Fruit
5: {
6: String color;
7: double weight;
8:
9: public Fruit ( String c, double w ) // Fruit constructor
10: {
11: color = c;
12: weight = w;
13: }
14:
15: public void describe ()
16: {
17: System.out.println( "I am " + color +
18: " and I weigh " + weight + " pounds." );
19: }
20: }
21:
22:
23: class Apple extends Fruit
24: {
25: public Apple ( String color, double weight )
26: {
27: super( color, weight );
28: }
29:
30: public void cost ()
31: {
32: System.out.println( "I'm an Apple that costs $" +
33: (0.30 * weight) + "." );
34: }
35: }
36:
37:
38: class Pear extends Fruit
39: {
40: public Pear ( String color, double weight )
41: {
42: super( color, weight );
43: }
44:
45: public void cost ()
46: {
47: System.out.println( "I'm a Pear that costs $" +
48: (0.25 * weight) + "." );
49: }
50: }
51:
52:
53: public class Fruit1
54: {
55: public static void main ( String [] args )
56: {
57: Apple a = new Apple( "red", 0.2 );
58: Pear p = new Pear( "yellow", 0.15 );
59: a.describe();
60: a.cost();
61: p.describe();
62: p.cost();
63: }
64: }