2012-07-07 117 views
2

我有一個布爾方法傳遞布爾方法執行到另一個類 - java的

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

你能更清楚一切應該在哪裏嗎?我懷疑答案是使用'this',但它很不明確。 – 2012-07-07 15:43:37

+0

你可以傳遞一個對象,你可以傳遞一個方法調用的結果,但是你不能傳遞一個方法。請在更高的層面解釋你想達到的目標。 – 2012-07-07 15:48:17

+0

您應該使用'equals'方法,而不是'=='來比較字符串。 – casablanca 2012-07-07 15:54:10

回答

1

與函數式語言不同,在像Java這樣的面向對象的語言中,不會傳遞函數,而是傳遞可以調用方法的對象。有幾種方法可以讓您的布爾方法對Car類可見。我打算撥打方法canAddCar只是爲了避免與Car#addCar混淆。

最簡單的是,如果你能在汽車類本身定義的方法:

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 { 
     // ... 
    } 
    } 
} 

還有其他幾種方法(匿名類,單類,靜態方法),但這些是最常見的,應讓你開始。

相關問題