[英]Difference between the two methods of reference variables
public class Player {
}
public class main {
public static void main(String []args) {
Player p1 ;
Player p2 = new Player();
}
}
在以下程序中,使用Player p1
和Player p2 = new Player();
創建變量之間有什么區別Player p2 = new Player();
???
我對此感到困惑。
提前致謝
在類中創建對象分為三部分。
玩家p2 = new Player(); 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.
當你說玩家p1時; 就像使用其他任何語言一樣,您只需創建Player類型的引用變量。 Player p2=new Player();
在這里p2被聲明,實例化和初始化。
注意:p2的對象是在使用新關鍵字時創建的,並且始終在堆內存中創建。 因此,您可以通過。(Dot)運算符對其成員進行操作。
P1只是一個參考,沒有分配任何對象(您可以在稍后階段使用它)。
P2是通過“ new player()”分配的對象的引用。
玩家p2 = new Player(); 它使用“ Player”類中的構造函數初始化p2。
玩家p1; 這不會產生新的Player對象。
http://msdn.microsoft.com/zh-cn/library/x9afc042.aspx閱讀了“創建對象”會話以了解更多信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.