简体   繁体   中英

Having a little trouble understanding objects (Java)

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?

您在实例级别声明了Player类型的变量p1,p2,p3 ,并在startGame()方法中对其进行了初始化。

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.

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 .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM