我無法理解如何使用來自兩個不同類的多個同名方法(在這種情況下,是兩個相同的方法)。驅動程序類(計算機)利用 Model 和 Laptop 類來顯示來自用戶輸入的信息。在 Model 和 Laptop 中,有兩種名稱相同但參數不同的方法。我對在筆記本電腦中為 setModel 方法設置三個參考變量的內容感到困惑。我曾嘗試操作 setModel 方法的模型對象,但沒有成功。我是從 UML 圖寫的。Laptop 和 Model 之間存在聚合關系,具體來說 Model HAS-A 與 Laptop 的關系(Laptop 上有一個菱形與 Model 相連)。import java.util.*;public class Computer { public static void main (String[] args) { // local variables, can be accessed anywhere from the main method char input1 = 'Z'; String inputInfo; String brandName, modelName; double price, cpuSpeed; int ramSize; String line = new String(); // instantiate a Laptop object Laptop laptop1 = new Laptop(); printMenu(); //Create a Scanner object to read user input Scanner scan = new Scanner(System.in); do // will ask for user input { System.out.print("What action would you like to perform?\n"); line = scan.nextLine(); if (line.length() == 1) { input1 = line.charAt(0); input1 = Character.toUpperCase(input1); // matches one of the case statement switch (input1) { case 'A': //Add the laptop System.out.print("Please enter the laptop information:\n"); System.out.print("What is the laptop\'s brand?\n"); brandName = scan.nextLine(); laptop1.setBrand(brandName); System.out.print("What is the laptop\'s model?\n"); modelName = scan.nextLine();
2 回答

哆啦的時光機
TA貢獻1779條經驗 獲得超6個贊
這讓我感到困惑,我不會以這種方式實現它,但我被要求這樣做。
我用我的原始實現找到了解決方案
public void setModel(String newModel, double newCPU, int newRAM)
{
model.setModel(newModel);
model.setCPU(newCPU);
model.setRAM(newRAM);
}
然后我修復了 Model 對象的實例化
private Model model = new Model();
添加回答
舉報
0/150
提交
取消