0

I am trying to understand the difference between:

public class GuessGame {
Player p1;
Player p2;
Player p3;

and

public void startGame() {
p1 = new Player();
p2 = new Player();
p3 = new Player();

Basically, what do these both do in the program? I understand that the startGame method is for creating objects, but what is the first part of the program for?

Stephen-Wisniewski
  • 321
  • 1
  • 2
  • 13

4 Answers4

1

You declared your variables p1,p2,p3 of type Player at instance level and initializing all of them in startGame() method.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

The first part declares that you have three Player objects available for use in the class. In your startGame() method, you're initialising the Player objects.

helencrump
  • 1,351
  • 1
  • 18
  • 27
1

First part is calling declaration of object.

Declarations simply notify the compiler that you will be using name to refer to a variable whose type is type. Declarations do not instantiate objects. To instantiate a Player object, or any other object, use the new operator.

The second part is called Instantiating an Object

The new operator instantiates a new object by allocating memory for it. new requires a single argument: a constructor method for the object to be created. The constructor method is responsible for initializing the new object.

You can check official java tutorial on object creation for more info. Or here.

Kiki
  • 2,243
  • 5
  • 30
  • 43
0

Java is fully Object oriented language. Check this out: Object-oriented programming

For Java syntax take look at this: Java - Object & Classes

Tornike Shavishvili
  • 1,244
  • 4
  • 16
  • 35