Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Program 5 : In the below example of inheritance, class Bicycle is a base class, class MountainBike is a derived class that extends the Bicycle

Program 5: In the below example of inheritance, class Bicycle is a base class, class MountainBike is a derived class that extends the Bicycle class and class Test is a driver class to run the program.
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 +"
"
+ "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;
}
}
// driver class
public class Test {
public static void main(String args[])
{
MountainBike mb = new MountainBike(3,100,25);
System.out.println(mb.toString());
}
}
Note: We will add this later to the above program
//// overriding toString() method of Bicycle to print more info
@Override public String toString()
{
return (super.toString()+"
seat height is "
+ seatHeight);
}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Microsoft Visual Basic 2017 For Windows Web And Database Applications

Authors: Corinne Hoisington

1st Edition

1337102113, 978-1337102117

Students also viewed these Databases questions