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 trialJohn Marley
8,740 PointsWhat is the purpose of the code following the equals sign? Game game = new Game("")
I understand that the former Game refers to the class Game and that this instance is then called game. Is the code following the equals sign...
Game game = new Game("treehouse")
written simply in order to pass in the String parameter or does it serve another purpose? Having it equal a new instance of the Game class seems unnecessary - do I have to create a 'new' instance of the Game class at all?
Thank you.
2 Answers
Kourosh Raeen
23,733 PointsHi John - If you only write
Game game;
then you've declared a variable that can reference a Game object but you haven't instantiated any object yet. To instantiate the object you need to use the new
keyword followed by the name of the class and the parenthesis. What that really does is that it calls the constructor that creates the object. In this case, the constructor takes a String parameter. Sometimes you see code like this:
Game game = new Game();
Here we are using the default constructor which creates an instance of Game. All classes, automatically get the default constructor even if you don't define it yourself, but if you want other constructors that take parameters you need to write those yourself.
Huggins Tatenda Mafigu
7,091 Pointsthe code following after the equal sign is for instantiating a class Foo f=new Foo(); this is the instatiation of an new class that takes no arguments Game game=new Game("Pez"); this is the instatiation of a class that takes an argument from the user
John Marley
8,740 PointsJohn Marley
8,740 PointsThank you, that makes more sense now. I'll revisit the earlier stages of the course until I understand all the terminology :)
Kourosh Raeen
23,733 PointsKourosh Raeen
23,733 PointsMy pleasure! Happy coding!