|
| 1 | +abstract class Car{ |
| 2 | + String color; |
| 3 | + abstract double speed(); |
| 4 | + abstract public String toString(); |
| 5 | + public Car(String color) |
| 6 | + { |
| 7 | + System.out.println("Car constructor called"); |
| 8 | + this.color=color; |
| 9 | + } |
| 10 | + //concrete method |
| 11 | + public String getColor() |
| 12 | + { |
| 13 | + return color; |
| 14 | + } |
| 15 | +} |
| 16 | +class Audi extends Car{ |
| 17 | + double speed; |
| 18 | + public Audi(String color,double speed) |
| 19 | + { |
| 20 | + super(color); |
| 21 | + System.out.println("Audi constructor called"); |
| 22 | + this.speed=speed; |
| 23 | + } |
| 24 | + double speed() |
| 25 | + { |
| 26 | + return speed; |
| 27 | + } |
| 28 | + public String toString() |
| 29 | + { |
| 30 | + return "Audi Color:"+super.color+" speed:"+speed(); |
| 31 | + } |
| 32 | + |
| 33 | +} |
| 34 | + |
| 35 | +class Mercedes extends Car { |
| 36 | + |
| 37 | + double distance; |
| 38 | + double time; |
| 39 | + |
| 40 | + public Mercedes(String color, double distance, double time) { |
| 41 | + // calling Shape constructor |
| 42 | + super(color); |
| 43 | + System.out.println("Mercedes constructor called"); |
| 44 | + this.distance = distance; |
| 45 | + this.time = time; |
| 46 | + } |
| 47 | + |
| 48 | + @Override |
| 49 | + double speed() { |
| 50 | + return distance/time; |
| 51 | + } |
| 52 | + |
| 53 | + @Override |
| 54 | + public String toString() { |
| 55 | + return "Mercedes color is " + super.color + "and speed is : " + speed(); |
| 56 | + } |
| 57 | + |
| 58 | +} |
| 59 | + |
| 60 | +public class Abstraction { |
| 61 | + public static void main(String[] args) { |
| 62 | + Car s1 = new Audi("Red", 2.2); |
| 63 | + Car s2 = new Mercedes("Yellow", 2, 4); |
| 64 | + |
| 65 | + System.out.println(s1.toString()); |
| 66 | + System.out.println(s2.toString()); |
| 67 | + } |
| 68 | +} |
0 commit comments