对象作为参数

时间:2015-10-29 09:59:20

标签: java

我试着:

  • Car
  • 中创建Main个对象
  • 将对象作为参数发送到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);
    }
}

2 个答案:

答案 0 :(得分:2)

覆盖Car,因此您可以自定义public String toString(){ return "Model :" + this.model + ",Year :" + year; }

的输出格式
{{1}}

答案 1 :(得分:0)

你的问题在这里:

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

您想要打印一个对象。这不起作用,因为Java使用toString-Method。如果你想这样做,你必须覆盖toString() - 你的汽车类的方法:

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