我有一个布尔方法
public boolean addCar(CarReg carReg, Car car){
return ?;
}
上述方法是为了传递给实际检查的另一个类
public class Car{
Map<CarReg, Car> carMap = new HashMap<carReg, Car>();
//if the check is successfull, the details are added to the collection
public boolean addCar(CarReg carReg, Car car){
If (garage.getOwner().toString == "pete"){
carMap.put(carReg, car);
return true;
}
}
}
我可以通过说car.addCar(carReg,car)来调用它吗? 实际上,我已经尝试过,但它似乎没有用。除非错误在其他地方。
答案 0 :(得分:1)
与函数式语言不同,在Java等面向对象语言中,您不会传递函数,而是传递可以调用方法的对象。有几种方法可以让您的布尔方法对Car类可见。我将调用方法canAddCar
,以避免与Car#addCar
混淆。
最简单的是你可以在Car类本身中定义方法:
public class Car {
public boolean canAddCar(CarReg carReg, Car car) {
// logic for checking if you can add the car
}
public boolean addCar(CarReg carReg, Car car) {
if (canAddCar(carReg, car)) {
// logic for adding the car goes here
return true;
} else {
// anything special if you can't add the car?
return false;
}
}
}
下一个最简单的方法是,如果您可以在传入的对象的类中定义方法,例如CarReg
这是有道理的,如果carReg负责检查您是否可以添加汽车。根据命名,我想你可能也希望carReg也负责添加汽车,但我没有在这里显示:
public class CarReg {
public boolean canAddCar(Car car) {
// logic for testing if you can add the car, for example:
return (car.getOwner().toString().equals("pete"));
}
}
public class Car {
public boolean addCar(CarReg carReg, Car car) {
if (carReg.canAddCar(car)) {
// ...
} else {
// ...
}
}
}
接下来,您可以将另一个对象传递给您的班级,该班级可以负责检查。
这可以是方法addCar
的另一个对象,或Car
类的属性。我在这个例子中展示了后者(因为前面的例子基本上是前者):
// might as well use an interface if you'll have multiple methods of checking
public interface CarChecker {
boolean canAddCar(CarReg carReg, Car car);
}
// specific implementation of the CarChecker interface
// you can instantiate this and pass it into the Car class via a setter
public class MyCarChecker implements CarChecker {
public boolean canAddCar(CarReg carReg, Car car) {
// checking logic goes here
}
}
public class Car {
private CarChecker carChecker;
// you'll have to implent getCarChecker and setCarChecker
// (or let your IDE generate the getters and setters)
// assuming you'll call setCarChecker somewhere (or have it wired up via IoC)
public boolean addCar(CarReg carReg, Car car) {
if (carChecker.canAddCar(carReg, car)) {
// ...
} else {
// ...
}
}
}
还有其他几种方法(匿名类,单例类,静态方法),但这些方法是最常见的,应该可以帮助您入门。