Please its a Java question under OBJECTS AND CLASS 1. Create a class that uses t
ID: 3601287 • Letter: P
Question
Please its a Java question under OBJECTS AND CLASS
1. Create a class that uses the Bicycle class: *Call the class BicycleDemo.java *BicycleDemo.java must be in the same directory as Bicycle.java *Compile with javac *.java 2. Create two new Bicycle objects using constructors: *no-arg constructor *constructor with arguments 3. Use accessors and mutators: *set gear and speed of bike 1 *set gear and speed of bike 2 *get gear and speed of bike 1 *get gear and speed of bike 2 4. Attempt to access members directly from demo program. What happens?
Explanation / Answer
Bicycle.java
public class Bicycle {
//Declaring instance variables
private int gear;
private int speed;
//Zero argumented constructor
public Bicycle() {}
//Parameterized constructor
public Bicycle(int gear, int speed) {
super();
this.gear = gear;
this.speed = speed;
}
//getters and setters
public int getGear() {
return gear;
}
public void setGear(int gear) {
this.gear = gear;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
//toString method is used to display the contents of an object inside it
@Override
public String toString() {
return "Bicycle [Gear=" + gear + ", Speed=" + speed + "kmph ]";
}
}
_________________
BicycleDemo.java
public class BicycleDemo {
public static void main(String[] args) {
//Creating an Bike class
Bicycle b1 = new Bicycle();
//calling the setter methods by passing values as arguments
b1.setGear(4);
b1.setSpeed(80);
//Displaying the bike class info
System.out.println("Bike#1: Gear=" + b1.getGear() + " Speed=" + b1.getSpeed() + " kmph");
//Creating an Bike class
Bicycle b2 = new Bicycle();
//calling the setter methods by passing values as arguments
b2.setGear(2);
b2.setSpeed(40);
//Displaying the bike class info
System.out.println("Bike#2: Gear=" + b2.getGear() + " Speed=" + b2.getSpeed() + " kmph");
}
}
_________________
Output:
Bike#1: Gear=4 Speed=80 kmph
Bike#2: Gear=2 Speed=40 kmph
_____________Could you rate me well.Plz .Thank You