user3654045 user3654045 - 6 months ago 12
Java Question

Interactions between two classes in OOP

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.

Answer

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:

  • If you don't know the number of slots in advance, you either can't use it at all or you'd be forced to create a large number of slots to cover the worst case.
  • If your garage's capacity changes in the future, you will have to manually add slot3/4/... to your garage class as well as update your entire code base to now also take into account slots 3/4/.. wherever garage is used.
  • Perhaps you don't care about the particular slots your cars are parked in, but you are simply interested in what cars your garage contains.

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

  1. Initialize parkedCars in Garage's constructor.
  2. Park cars by calling the LinkedList.Add method inside Car.Park.

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.

Comments