2015-10-29 27 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; 
}