|
| 1 | + |
| 2 | +edit |
| 3 | +play_arrow |
| 4 | + |
| 5 | +brightness_5 |
| 6 | +//Java program to illustrate the |
| 7 | +// concept of inheritance |
| 8 | + |
| 9 | +// base class |
| 10 | +class Bicycle |
| 11 | +{ |
| 12 | + // the Bicycle class has two fields |
| 13 | + public int gear; |
| 14 | + public int speed; |
| 15 | + |
| 16 | + // the Bicycle class has one constructor |
| 17 | + public Bicycle(int gear, int speed) |
| 18 | + { |
| 19 | + this.gear = gear; |
| 20 | + this.speed = speed; |
| 21 | + } |
| 22 | + |
| 23 | + // the Bicycle class has three methods |
| 24 | + public void applyBrake(int decrement) |
| 25 | + { |
| 26 | + speed -= decrement; |
| 27 | + } |
| 28 | + |
| 29 | + public void speedUp(int increment) |
| 30 | + { |
| 31 | + speed += increment; |
| 32 | + } |
| 33 | + |
| 34 | + // toString() method to print info of Bicycle |
| 35 | + public String toString() |
| 36 | + { |
| 37 | + return("No of gears are "+gear |
| 38 | + +"\n" |
| 39 | + + "speed of bicycle is "+speed); |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +// derived class |
| 44 | +class MountainBike extends Bicycle |
| 45 | +{ |
| 46 | + |
| 47 | + // the MountainBike subclass adds one more field |
| 48 | + public int seatHeight; |
| 49 | + |
| 50 | + // the MountainBike subclass has one constructor |
| 51 | + public MountainBike(int gear,int speed, |
| 52 | + int startHeight) |
| 53 | + { |
| 54 | + // invoking base-class(Bicycle) constructor |
| 55 | + super(gear, speed); |
| 56 | + seatHeight = startHeight; |
| 57 | + } |
| 58 | + |
| 59 | + // the MountainBike subclass adds one more method |
| 60 | + public void setHeight(int newValue) |
| 61 | + { |
| 62 | + seatHeight = newValue; |
| 63 | + } |
| 64 | + |
| 65 | + // overriding toString() method |
| 66 | + // of Bicycle to print more info |
| 67 | + @Override |
| 68 | + public String toString() |
| 69 | + { |
| 70 | + return (super.toString()+ |
| 71 | + "\nseat height is "+seatHeight); |
| 72 | + } |
| 73 | + |
| 74 | +} |
| 75 | + |
| 76 | +// driver class |
| 77 | +public class Test |
| 78 | +{ |
| 79 | + public static void main(String args[]) |
| 80 | + { |
| 81 | + |
| 82 | + MountainBike mb = new MountainBike(3, 100, 25); |
| 83 | + System.out.println(mb.toString()); |
| 84 | + |
| 85 | + } |
| 86 | +} |
0 commit comments