Say for example I have a class called Phone.
What is the difference between:
Phone p;
and
Phone p = new Phone(200)
The first snippet only declares a variable p
with a given type Phone
. You have not created any object, only a variable.
The third instantiates a new Phone
object (which is not assigned to a variable).
The second combines the two, the declaration and instantiation, into a single line of code.
Phone p; // declaration of variable
p = new Phone(200); // instantiation of object, assigned to variable
Phone p = new Phone(200); // declaration and instantiation in a single line
For p
to be used, you need to instantiate it (or otherwise initialize it). The declaration itself is not useful. In a local (a variable declared inside the scope of a method), it is illegal to use it without first initializing it. If it's a class-level member, then it will simply be a null pointer when you try to access any of its member functions.