user3323950
user3323950

Reputation: 207

how does the new keyword work if you dont give it a name?

I'm learning the Builder Pattern design pattern. I understand most of it but I'm just having confusion with the new keyword. In this tutorial, in the MealBuilder class, he creates an object of type Meal, and then calls a method addItem(...) using that object. I don't understand what he passes in the parameter. I understand that the new keyword creates an instance (is instance another word for creating an object?) of a class but he didn't name it. E.g. I understanding the following: Meal mealobject = new Meal(); but I dont understand this: new ChickenBurger();

Upvotes: 1

Views: 95

Answers (1)

Shaun the Sheep
Shaun the Sheep

Reputation: 22742

If you wrote

Meal meal = new Meal();
Item burger = new ChickenBurger();
meal.addItem(burger);

then this would behave the same way. However, if you aren't going to user the "burger" reference again, then there's no point in creating it. Just writing

Meal meal = new Meal();
meal.addItem(new ChickenBurger());

is simpler and makes it obvious to someone reading the code that the item is only being added to the collection (the meal).

Note that this isn't a hard rule. There may be some situations where you might decide that using a named reference for an expression will help clarify what the code is doing, particularly if it's not clear from the data types.

Upvotes: 2

Related Questions