why is my code returning a null value at the last output ?
I it is supposed to return this: Auto MERCEDES C from Garage: TOP SERVICE (x2)
Actualy, the full output should be :
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: TOP SERVICE
I know the problem is somewhere in my contructor that conctruct a copy of my object.
Thank you
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);
}
}
You haven’t implemented your copy constrictor right in the
Autoclass.As of now, it just calls the
hashCode()method but doesn’t initialize the class attributes:Please correct it as below:
Once done then
Auto kopie = new Auto(auto);statement will result into new class instancekopiewith atributes copied fromautoinstance.