Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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*

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!");
    ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading