Labs
We will change the Car class to use better encapsulation, and then fix a test class that uses Car. Finally, we will create a class that stores Car objects.
-
Copy the
Carclass fromcom.example.encapsulation.referenceintocom.example.encapsulation.labs; you must create the package if you have not already. -
Change the
Carclass's fields to haveprivatevisibility. - Add getters and setters for the fields.
- Add a constructor with parameters for all five fields.
- Add a no-arg constructor.
-
Change the name of the method
getCarDatatotoString(because it is not a getter). -
Copy
CarTesterfromcom.example.encapsulation.referenceintocom.example.encapsulation.labs. -
The class is broken. Change it to use getters and setters.
-
Create a class called
ParkingLot. Its job is to hold an array of cars. The class will have: - A field for a
Car[]. This field is of courseprivate. private static int MAX_CARS = 100;.- A no-arg constructor. In this constructor, initialize the
Car[]to have space for 100Carreferences. -
Two methods.
-
void addCar(Car car). This adds a Car to the array. (How will you decide the next available array location? You probably need to keep track of the number of cars in the array.)Users outside the package should be able to use this method.
-
Car[] getCars(). This returns a reference to theCar[]inParkingLot.Users outside the package should be able to use this method.
-
-
Create a class called
ParkingLotTester. This class will have amainmethod. -
Create a
ParkingLotinstance. - Call
getCarsand verify that an array of the correct length is returned (by printing itslengthto the screen). - Iterate through the array to verify that it contains
nullvalues. - Create several
Carinstances and add them to theParkingLot. - Call
getCarsto get the array of Cars. - Verify that
getCarsstill returns an array of the same length. - Iterate through the array and have each
Cardisplay itself. (Be careful of attempting to call a method on anullreference.)
Stretch Goals¶
Car[] getCars(). Return an array containing all Cars in the ParkingLot. It does not just return the private reference. It will instead return a different array containing all Cars in the ParkingLot; the array does not have any null elements.