Question
Question: Using the program below, add encapsulation to it to include making all attributes private, adding constructor, and adding get and set methods. The main
Question: Using the program below, add encapsulation to it to include making all attributes private, adding constructor, and adding get and set methods. The main method should create an instance of the class and demonstrate the correct functionality of all the methods.
class Car { int speed;
public void accelerate(int increment) { speed += increment; System.out.println("Speed increased to " + speed + " km/h."); } }
class MyDriver { public static void main(String[] args) { Car myCar = new Car(); myCar.speed = 60; System.out.println("Initial speed: " + myCar.speed + " km/h."); myCar.accelerate(20); System.out.println("Final speed: " + myCar.speed + " km/h."); } }
Expected Output:
When you run this program you will see the following output:
Initial speed: 60 km/h. Speed increased to 80 km/h. Final speed: 80 km/h.
This demonstrates that the value of the "speed" attribute was successfully changed from 60 to 80 km/h, and that the "accelerate" method successfully completed what it was supposed to do by increasing the speed by 20 km/h.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started