简体   繁体   English

难以理解对象(Java)

[英]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? 我知道startGame方法用于创建对象,但是程序的第一部分是做什么的?

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

The first part declares that you have three Player objects available for use in the class. 第一部分声明您在类中可以使用三个Player对象。 In your startGame() method, you're initialising the Player objects. startGame()方法中,您正在初始化Player对象。

First part is calling declaration of object . 第一部分是调用object的声明

Declarations simply notify the compiler that you will be using name to refer to a variable whose type is type. 声明只是通知编译器您将使用name来引用类型为type的变量。 Declarations do not instantiate objects. 声明不实例化对象。 To instantiate a Player object, or any other object, use the new operator. 要实例化Player对象或任何其他对象,请使用new运算符。

The second part is called Instantiating an Object 第二部分称为实例化对象

The new operator instantiates a new object by allocating memory for it. new运算符通过为其分配内存来实例化一个新对象。 new requires a single argument: a constructor method for the object to be created. new需要一个参数:要创建的对象的构造方法。 The constructor method is responsible for initializing the new object. 构造函数方法负责初始化新对象。

You can check official java tutorial on object creation for more info. 您可以查看有关对象创建的官方Java教程以了解更多信息。 Or here . 还是这里

Java is fully Object oriented language. Java是完全面向对象的语言。 Check this out: Object-oriented programming 检查一下: 面向对象的编程

For Java syntax take look at this: Java - Object & Classes 对于Java语法,请查看以下内容: Java-对象和类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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