两种参考变量方法的区别

时间:2014-09-28 06:56:01

标签: java reference

public class Player {
}

public class main {
    public static void main(String []args) {
      Player p1 ;
      Player p2 = new Player();
    }
}

在以下程序中,使用Player p1Player p2 = new Player();创建变量有什么区别?

我对那部分很困惑。

提前致谢

3 个答案:

答案 0 :(得分:2)

在类中创建对象有三个部分。

玩家p2 =新玩家(); 1.Declaration: The code set in bold are all variable declarations that associate a variable name with an object type. 2. Instantiation: The new keyword is a Java operator that creates the object. 3. Initialization: The new operator is followed by a call to a constructor, which initializes the new object.

当你说Player p1;就像在任何其他语言中一样,您只需创建一个Player类型的引用变量。 Player p2=new Player();

此处p2已声明,实例化并初始化。

注意:p2的对象是在使用new关键字时创建的,并且始终在堆内存中创建。因此,您可以通过。(点)运算符对其成员进行操作。

答案 1 :(得分:1)

P1只是一个参考,没有指定对象(你可以在以后的阶段使用它)。
P2是通过" new player()"。

分配对象的引用

答案 2 :(得分:1)

玩家p2 =新玩家(); 这使用了类#34; Player"中的构造函数。初始化p2。

玩家p1; 这不会产生新的Player对象。

http://msdn.microsoft.com/en-us/library/x9afc042.aspx 阅读创建对象会话以获取更多信息