From 04d3fb6d3b084e5e4b4be82167c6edcb3db14a38 Mon Sep 17 00:00:00 2001 From: Duggineni Sukanya Date: Mon, 1 Oct 2018 18:54:29 +0530 Subject: [PATCH] inheritance in depth example --- .../oops/interfaces/InterfaceExamples.java | 102 +++++++++++++----- 1 file changed, 78 insertions(+), 24 deletions(-) diff --git a/src/com/in28minutes/java/oops/interfaces/InterfaceExamples.java b/src/com/in28minutes/java/oops/interfaces/InterfaceExamples.java index aa24355..cb8f4dd 100644 --- a/src/com/in28minutes/java/oops/interfaces/InterfaceExamples.java +++ b/src/com/in28minutes/java/oops/interfaces/InterfaceExamples.java @@ -1,24 +1,78 @@ -package com.in28minutes.java.oops.interfaces; - -interface Flyable { - void fly(); -} - -class Aeroplane implements Flyable { - public void fly() { - System.out.println("Aeroplane is flying"); - } -} - -class Bird implements Flyable { - public void fly() { - System.out.println("Bird is flying"); - } -} - -public class InterfaceExamples { - public static void main(String[] args) { - Flyable flyable = new Bird(); - flyable.fly(); - } -} +// base class +class Bicycle +{ + // the Bicycle class has two fields + public int gear; + public int speed; + + // the Bicycle class has one constructor + public Bicycle(int gear, int speed) + { + this.gear = gear; + this.speed = speed; + } + + // the Bicycle class has three methods + public void applyBrake(int decrement) + { + speed -= decrement; + } + + public void speedUp(int increment) + { + speed += increment; + } + + // toString() method to print info of Bicycle + public String toString() + { + return("No of gears are "+gear + +"\n" + + "speed of bicycle is "+speed); + } +} + +// derived class +class MountainBike extends Bicycle +{ + + // the MountainBike subclass adds one more field + public int seatHeight; + + // the MountainBike subclass has one constructor + public MountainBike(int gear,int speed, + int startHeight) + { + // invoking base-class(Bicycle) constructor + super(gear, speed); + seatHeight = startHeight; + } + + // the MountainBike subclass adds one more method + public void setHeight(int newValue) + { + seatHeight = newValue; + } + + // overriding toString() method + // of Bicycle to print more info + @Override + public String toString() + { + return (super.toString()+ + "\nseat height is "+seatHeight); + } + +} + +// driver class +public class Test +{ + public static void main(String args[]) + { + + MountainBike mb = new MountainBike(3, 100, 25); + System.out.println(mb.toString()); + + } +} \ No newline at end of file