Reputation: 77
I am trying to learn OOP in JAVA. I wanted to make a simple OOP based console application. The whole application is just about two classes: Car and Garage.
This is my Garage class:
public class Garage {
private int capacity;
}
And this is my Car class:
public class Car {
private String type;
private String color;
public Auto(String type, String color){
this.color = color;
this.type = type;
}
public String getColor(){
return color;
}
public String getType(){
return type;
}
public void Park(Garage garage){
}
}
What I don't know is how to make them interact between each other. That means that I don't know how to make the Park() method. The method should simple park the car into the garage, so I could write down all the cars parked in the garage later.
Upvotes: 0
Views: 1374
Reputation: 223
In your Garage class, you could add a list to keep track of the cars in the garage.
private List<Car> carsParked;
//just using arraylist as an example you could use any other of list or even a set if you so wish
public Garage() {
carsParked = new ArrayList<>();
}
and then add Cars to your garage using say an addCar method:
public void addCar(Car c) {
carsParked.add(c);
}
In your park method in the Car class, do something like:
public void park(Garage g) {
g.addCar(this);
}
Upvotes: 2
Reputation:
You need a way to store the cars in your garage. If you knew your garage's capacity in advance (say 2), you could 'hard-code' the cars inside it:
class Garage {
Car slot1;
Car slot2;
}
void Park(Garage g) {
if (g.slot1 == null) {
g.slot1 = this;
} else if (g.slot2 == null) {
g.slot2 = this;
}
}
If you'd like to output all cars inside your garage you can do so by testing each slot for NULL (and only printing the non-null slots).
This is not a very good solution:
For this purpose we have 'Collections' in Java. They allow us to store arbitrary numbers of objects of a certain type in one variable. One example is a LinkedList. I'll get you started on how to use it:
class Garage {
LinkedList<Car> parkedCars;
}
Now you have to
Once you solve these two problems, consider what happens if you park the same car multiple times in a row. Is this outcome desired? Have a look at HashSet.
Upvotes: 0