Emz
Emz

Reputation: 1280

How to Instantiate Game

I see this piece of code in almost every game example for Java. Create an instance of the Game class then execute the loop from that instance.

public static void main(String[] args) {
    Game g = new Game();
    g.gameLoop();
}

public Game () {
}

However, as I don't do anything apart from the execution of the gameLoop() why not write it like this? I don't really need to store the instance of Game anywhere do I? Like this.

public static void main(String[] args) {
    new Game ();
}

public Game () {
    gameLoop();
}

If so for what?

Both cases are working and have been tested by me.

Upvotes: 4

Views: 148

Answers (2)

user3437460
user3437460

Reputation: 17454

if you write it like this:

new Game ();

This is done by using a constructor. A constructor's main purpose is to create objects and initialize any variables and set any initial value you need to set.

If you only write new Game(), it can compile, but doesn't mean it is a good way to implement. Why is it not a good implementation?

It is because doing so, you are as good as writing your entire game within the constructor. It is wrong to begin with, because you are actually not supposed to implement your entire logic in the constructor.

So why people do it as such:

Game g = new Game();
g.gameLoop();

Now, note the difference of this and the one you suggested (using a constructor). Doing so you modularize your codes into sub-problems. Benefit of modularization? Lots of it:

  • Easier to manage your codes
  • Easier to debug your codes, shorter debugging time
  • Write once, use it n times
  • Easier to read and maintain your codes

However, there are different ways you code with Java. It is also possible to make your gameLoop() static. So that you can do this (without instantiating an object):

Game.gameLoop();

This is possible, but I don't advise you doing this.

Upvotes: 3

matt forsythe
matt forsythe

Reputation: 3922

One reason is because of philosophy: constructors are for constructing things, not running them. But there is a practical concern as well. If you call gameLoop() inside of the constructor, then you have no way of creating a Game without running it. This could pose a problem if, say, you wanted to construct a game, then make some changes to its configuration, then run it. This scenario would make even more sense if you ended up subclassing Game.

Upvotes: 0

Related Questions