Issue
I have a class called Food.java that has two constructors. The driver code I have been given calls its copy constructor inside its constructor with its own object as the parameter. The copy constructor has the parameters food and flavor. This is an object is then printed out using a toString() method but the toString() method is giving me the food variable and the flavor variable are both null. Would anyone be able to tell me why? Thank you.
Driver code:
public static void main(String args[]) {
System.out.println(new Food(new Food("Ice-cream", "Vanilla")));
}
My code :
public class Food {
private String food;
private String flavor;
private Food f;
public Food(String food, String flavor) {
this.food = food;
this.flavor = flavor;
}
public Food(Food f) {
this.f = f;
}
public String toString() {
return food + " " + flavor;
}
}
Output:
null null
Solution
When you call System.out.println (new Food (new Food ("Ice-cream", "Vanilla"))); you are creating to Food instances. When the inner instance is created this constructor is called:
public Food(String food, String flavor) {
this.food = food;
this.flavor = flavor;
}
Here food and flavor are set. Then the outer Food instance is created with the other constructor. Here only f is set, not food and flavor. And the outer instance is thrown into the println, so this is the instance toString is called on. What you want is a constructor doing this:
public Food(Food other) {
this.food = other.food;
this.flavor = other.flavor;
}
And then you can delete the field f.
Answered By - user2999226
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.