Reputation: 85
public class Player {
}
public class main {
public static void main(String []args) {
Player p1 ;
Player p2 = new Player();
}
}
In the following program, what is the difference between creating variable using Player p1
and Player p2 = new Player();
???
I am confused at that part.
Thanks in advance
Upvotes: 0
Views: 40
Reputation: 125
Player p2 = new Player(); this uses the constructor in the class "Player" to initialize the p2.
Player p1; This doesn't make new Player object.
http://msdn.microsoft.com/en-us/library/x9afc042.aspx read the Creating Objects session for more information
Upvotes: 1
Reputation: 495
P1 is just a reference, no object assigned (you can use it later stage).
P2 is a reference with object assigned through "new player()".
Upvotes: 1
Reputation: 1395
There are three parts in creating an object in a class.
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.
when you say Player p1 ; just like in any other language, you just create a reference variable of type Player.
Player p2=new Player();
here p2 is been declared, instantiated and initialized.
Note: the object for p2 is created when a new keyword is used and are always created in heap memory. Thus you can operate on its members through the .(Dot) operators.
Upvotes: 2