为什么我的代码在最后一次输出时返回空值? 我应该归还这个:来自车库的汽车MERCEDES C:TOP SERVICE(x2) Actualy,完整输出应该是: 来自车库的Auto FORD S-MAX:SPEEDY 来自车库的Auto FORD FOCUS:SPEEDY 来自车库的Auto MERCEDES C:TOP SERVICE 来自车库的Auto MERCEDES C:TOP SERVICE
我知道问题出在我的构造函数中,它可以构建我的对象的副本。 谢谢
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);
}
}
答案 0 :(得分: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
实例复制。