2015-10-29 103 views
1

我嘗試:對象作爲參數

  • 創建於Main一個Car對象。
  • 將該對象作爲參數發送到carOwners類。
  • 從main打印整個carOwners數據。

NameAddress將被打印,但不是Car

我的代碼有什麼問題?

public class TestProgram { 
    public static void main(String [] args){ 
     Car Saab = createCar(); 
     carOwners guy = createCarOwners (Saab); 
     printAll(guy); 
    } 

    public static Car createCar(){ 
     //user input a, b, c, d 
     Car temporary = new Car (a, b, c, d); 
     return temporary; 
    } 
    public static carOwners createCarOwners (Car x){ 
     //user input a, b 
     Car c = x; 
     carOwners temporary = new carOwners (a, b, c); 
     return temporary; 
    } 

    public static void printAll (carOwners x){ 
     x.printCarData(); 
     x.printNameAddress(); 
    } 
} 

public class Car { 
    private String model; 
    private String Year; 
    private String licensePlate; 
    private String color; 

    public Car (String x, int y, String z, String q){ 
     model = x; 
     Year = y; 
     licensePlate = z; 
     color = q; 
    } 
} 

public class carOwners { 
    private String name; 
    private String address; 
    private Car TheCar; 

    public carOwners (String n, String a, Car b){ 
     name = n; 
     address = a; 
     TheCar = b; 
    } 

    public void printNameAddress(){ 
     System.out.println(); 
     System.out.println(name); 
     System.out.println(address); 
    } 

    public void printCarData(){ 
     System.out.println(TheCar); 
    } 
} 
+0

您將*引用傳遞給對象*到其他方法。 – TheLostMind

+3

覆蓋'Car'類中的'Object#toString'。 – Mena

+1

你應該養成爲你的變量賦予有意義名稱的習慣 – JonK

回答

0

你的問題的輸出格式是在這裏:

public void printCarData(){ 
     System.out.println(TheCar); 
    } 

您想打印一個對象。這並不奏效,因爲Java使用toString-Method。如果你想這樣做,你必須重寫toString() - 你的汽車類的方法是這樣的:

public String toString() 
{ 
    return "CarModel: " + this.model + ", Production Year: " + year; 
} 
2

覆蓋toString(),所以你可以自定義的Car

public String toString(){ 
    return "Model :" + this.model + ",Year :" + year; 
}