Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java

Borislav Milev
Borislav Milev
1,218 Points

What does the "new" keyword do and how to use it?

Can someone explain to me in the most simple way what does "new" do. Thank you.

1 Answer

The new keyword makes a new instance of a class.

Classes are very confusing for beginners. Even myself was extremely confused when I was learning this topic. However, I'll try to make it easy-to-understand by using examples. :grin:

Think of a class as a cookie cutter. A cookie cutter is basically a blueprint; when you are making cookies, you use the cookie cutter to make cookies, you don't eat the cookie cutter itself. In this case, the cookie cutter makes "instances" of itself.

When you use (eat) a cookie, you don't eat the cookie cutter itself; you use that to make the cookies. You eat the "instances" of the cookie cutter (the cookies) instead.

Another example: You have a Car class. Remember, a class is just a blueprint of something, in this case our class is modeling what a car would be. We can use this class to make instances of itself, basically saying that "you use the model to make the car". I know it's confusing...

Remember that you are free to make as many instances as you want :smile:

Example in code:

public class Car {
  public static void Car(name, color) {
    this.speed = 0;
    this.brand = brand;
    this.color = color;
  }
  public void pressTheGas() {
    this.speed += 10;
  }
  public void slowDown() {
    this.speed -= 10;
  }
  public int getSpeed() {
    return this.speed;
  }
}

// Over here we're going to make new instancea of Car! Remember, this is
// "Making a cookie using the cookie cutter" where the class is the cutter and the new
// instance is the cookie.

Car honda = new Car("Honda", "Black");
Car jeep = new Car("Jeep", "Blue");
Car tesla = new Car("Tesla", "Red");

I hope this helps you out! :grin:

~Alex :sparkles:

Borislav Milev
Borislav Milev
1,218 Points

Thank you very much! Now I understand what it means, you are a lifesaver!