I cannot understand this very simple code

I’m kinda new at coding and I was wondering if someone could explain this simple code to me like I was a 5 year old.

Why this code executes "Hello" instead of "Goodbye"?

Main.java*

public class Main {
    public static void main(String[] args) {
 
    ...

    Store store = new Store();
    store.setDessert(cake, 1);
 
    }
}

Dessert.java

public class Dessert {
 
    ...
 
public Dessert(double price, String[] ingredients) {
    System.out.println("Hello!");
    ...
}

public Dessert(Dessert source) {
    System.out.println("Goodbye!");
    ...
}

public double getPrice() {
    return this.price;
}

public String[] getIngredients() {
    return Arrays.copyOf(this.ingredients, this.ingredients.length);
}
 
}

Store.java

public class Store {



...

public void setDessert(Dessert dessert, int index) {
    this.desserts[index] = new Dessert(dessert.getPrice(), dessert.getIngredients());
}
}

>Solution :

you have two constructors on Dessert Class, the first one with two parameters and the second with on parameter :

public Dessert(double price, String[] ingredients) {
    System.out.println("Hello!");
    ...
}

public Dessert(Dessert source) {
    System.out.println("Goodbye!");
    ...
}

When you instantiate Dessert in the setDessert method in the Store class :

new Dessert(dessert.getPrice(), dessert.getIngredients());

you are calling the contructor with two parameters because you gave to arguments and then that constructor have to print hello world.

public Dessert(double price, String[] ingredients) {
    System.out.println("Hello!");
    ...
}

Leave a Reply