Classes and UML Lab
Classes in Java and their representation in UML.
Categories:
2 minute read
Introduction
The goal for this activity is to implement a Car class so that it conforms to the UML below:
classDiagram
class Car
Car: -String make
Car: -int year
Car: -double speed
Car: +Car(m String, y int)
Car: +toString() String
Car: +getMake() String
Car: +getSpeed() double
Car: +getYear() int
Car: +accelerate() String
Car: +brake() void
ℹ️ Note
UML diagrams often omit the return type onvoid methods. While they’re present above, we’ll likely omit them in the future.Part 1: Driver, Constructor and toString
- Create two Java class files: CarTester.java and Car.java. Only CarTester.java should include a main method.
- Add the three instance variables from the UML diagram to
your
Carclass. - Code the constructor for your
Carclass. This should initialize themakeandyearfields using the arguments to the constructor. Thespeedshould be initialized to0. - Code the
toStringmethod. This method should take no parameters and should return aStringthat looks like this (except with the angle-bracketed parts replaced with this car's values):"A <year> <make> that is going <speed> mph" - Test your partially completed
Carclass by adding code to themainin CarTester.java that creates and prints two car objects. The contents ofmainshould look something like the following.Car car1; Car car2; car1 = new Car("Ford", 1997); car2 = new Car("Toyota", 2014); System.out.println(car1.toString()); System.out.println(car2.toString());
Part 2: Remaining Methods
Complete each of the remaining methods of the Car class.
Test each method by adding appropriate calls to main.
- The three "getter" methods should each return the value of the appropriate instance variable.
- The
acceleratemethod should increase the currentspeedof the car by 5.0 mph. It should also return aStringthat describes the change to thespeed, e.g."15.0 + 5.0 = 20.0". It should NOT be possible to increase the speed beyond 150.0 mph. If a call toacceleratewould push the speed beyond 150.0, the speed should be set to 150.0. (reaching this limit should be reflected in the returned String as well, i.e."150.0 + 0.0 = 150.0")(How will you test that this is working correctly? How many times do you need to call
acceleratebefore the upper speed limit is reached? Might a loop be helpful here?) - The
brakemethod should decrease the current speed by 5.0 mph. It should not be possible for the speed to drop below 0 mph.
Submit Car.java only to Gradescope per your section's deadline. Gradescope will run Checkstyle tests on your submission.
Acknowledgements
Thank you to Dr. Sprague for this activity.
Last modified January 16, 2025: Rename deploy.yml to dont_deploy.yml (7438dab)