我正在尝试在JAVA中学习OOP。我想制作一个简单的基于OOP的控制台应用程序。整个应用程序只有两个类:汽车和车库。
这是我的车库类:
public class Garage {
private int capacity;
}
这是我的Car类:
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){
}
}
我不知道的是如何让它们彼此互动。这意味着我不知道如何制作Park()方法。该方法应该简单地将车停放在车库中,这样我就可以记下以后停在车库里的所有车辆。
答案 0 :(得分:1)
在您的车库类中,您可以添加一个列表来跟踪车库中的车辆。
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<>();
}
然后使用addCar方法将汽车添加到您的车库:
public void addCar(Car c) {
carsParked.add(c);
}
在Car类的park方法中,执行以下操作:
public void park(Garage g) {
g.addCar(this);
}
答案 1 :(得分:0)
您需要一种存储汽车车库的方法。如果您事先知道车库的容量(比如说2),那么您可以对车内的车辆进行“硬编码”:
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;
}
}
如果您想输出车库内的所有车辆,可以通过测试每个插槽的NULL(并且只打印非空插槽)来实现。
这不是一个很好的解决方案:
为此,我们在Java中使用'Collections'。它们允许我们在一个变量中存储任意数量的特定类型的对象。一个例子是LinkedList。我会开始介绍如何使用它:
class Garage {
LinkedList<Car> parkedCars;
}
现在你必须
一旦解决了这两个问题,请考虑如果连续多次停放同一辆车会发生什么。这个结果是否合适?看看HashSet。