Difference between creating a “new object” and “Class objectname”

后端 未结 5 560
忘掉有多难
忘掉有多难 2021-01-06 15:03

Say for example I have a class called Phone.

What is the difference between:

Phone p;

and

Phone p = new Phone(200)          


        
5条回答
  •  南笙
    南笙 (楼主)
    2021-01-06 15:36

    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.

提交回复
热议问题