I am working on a project for university and we were told to move the code that was previously in main of the ‘Bakery Driver’ class to another class in a file called ‘Magic Bakery’ (also placing it in main). And in main of Bakery Driver, to create an object of the Magic Bakery class and so, the output should be the same (As the code in main of MagicBakery should be executed as the object is being created).
However, this is not the case. I have some print statements that were working when I ran the Bakery Driver file but now, after moving the code, these print statements are not executed. Does anyone know why?
I know the code in main of MagicBakery is working as it runs and I get the expected output.
This is the code:
BakeryDriver.java
import bakery.MagicBakery;
public class BakeryDriver {
public BakeryDriver() {
}
public static void main(String[] args) {
MagicBakery bakery = new MagicBakery();
}
}
MagicBakery.java
package bakery;
import java.util.ArrayList;
public class MagicBakery{
public MagicBakery(){
}
public static void main(String[] args){
Ingredient flour = new Ingredient("flour");
Ingredient sugar = new Ingredient("sugar");
Ingredient egg = new Ingredient("egg");
System.out.println(flour.toString());
System.out.println(sugar.toString());
System.out.println(egg.toString());
ArrayList<Ingredient> recipe_test = new ArrayList<Ingredient>();
recipe_test.add(flour);
recipe_test.add(sugar);
recipe_test.add(egg);
Layer layer_test = new Layer("testing yo", recipe_test);
System.out.print(layer_test.getRecipeDescription());
CustomerOrder order_test = new CustomerOrder("test", recipe_test, recipe_test, 0);
}
}
>Solution :
Your understanding is incorrect. Constructing an object runs the constructor, not main. The static main function is only called by the Java runtime when you run that class at your application’s entrypoint (or if you explicitly write MagicBakery.main(someStringArray)).
In your case, it sounds like you want the MagicBakery object to be able to do some things, so I would recommend changing your main in that class to something like
public CustomerOrder makeCustomerOrder() {
// Method body ...
}
Then, in your BakeryDriver.main, you can write
MagicBakery bakery = new MagicBakery();
bakery.makeCustomerOrder();