-1

为什么我的代码在最后一个输出中返回空值?我应该返回这个: Auto MERCEDES C from Garage: TOP SERVICE (x2) 实际上,完整的输出应该是: Auto FORD S-MAX from Garage: SPEEDY Auto FORD FOCUS from Garage: SPEEDY Auto MERCEDES C from Garage: TOP SERVICE Auto MERCEDES C from Garage:顶级服务

我知道问题出在我的构造函数的某个地方,它构造了我的对象的副本。谢谢

public class Garage {

    //final String naam;
    String naam;

    public Garage (String n){
        this.naam = n;
        }
    public String getName(){
        return naam;
    }

    public void setName(String sn){
        this.naam = sn;
    }

    public String toString(){
        return ""+getName(); 

    }

}

public class Auto {

    //static final String brandName; 
    String brandName;
    Garage garage;

    public Auto(String mn){
        this.brandName = mn;

    }
    public Auto(Auto a){
        this.hashCode();
    }
    public Auto(String mn, Garage g){
        //this(mn);
        this.brandName = mn;
        this.garage = g;
    }

    public String getBranName(){
        return brandName;
    }
    public Garage getGarage(){
        return garage;
    }

    public void setGarage(Garage g){
        this.garage = g;
    }

    public String toString(){
        return "Auto "+getBranName()+" from Garage: "+getGarage();
    }

}


public class GarageTester {

    /**
     * @param args
     */
    public static void main(String[] args) {

        Auto auto = new Auto("FORD S-MAX");
        Garage garage = new Garage("SPEEDY");
        auto.setGarage(garage);

        System.out.println(auto);

        auto = new Auto("FORD FOCUS",garage);

        System.out.println(auto);

        auto =  new Auto("MERCEDES C", new Garage("TOP SERVICE"));

        System.out.println(auto);

        Auto kopie = new Auto(auto);

        System.out.println(kopie);

    }

}
4

1 回答 1

1

你还没有在Auto课堂上实现你的复制限制器。

public Auto(Auto a){
    this.hashCode();
}

截至目前,它只是调用hashCode()方法但不初始化类属性:

请更正如下:

public Auto(Auto a){
    this.brandName = a.brandName;
    this.garage = a.garage;
}

一旦完成,则Auto kopie = new Auto(auto);语句将生成新的类实例kopie,其中包含从实例复制的属性auto

于 2012-12-01T21:02:00.123 回答