Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialBorislav Milev
1,218 PointsWhat 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
Alexander Davison
65,469 PointsThe 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.
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
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!
~Alex
Borislav Milev
1,218 PointsBorislav Milev
1,218 PointsThank you very much! Now I understand what it means, you are a lifesaver!