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

后端 未结 5 556
忘掉有多难
忘掉有多难 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:31

    Phone p;
    

    is just a reference or a "pointer" as some people liking C language would call it. It contains the path to an object but currently the path is null.

    Phone p = new Phone(200) //(200 is the price of the phone).
    

    Here you are creating a new Phone object, by calling its constructor which takes the 200 value. The object is then assigned to the reference p.

    new Phone(200)
    

    Here you are just creating an Object of type Phone but do not have a reference to it, so this object is in turn to be Garbage Collected by the JVM (if not referenced to something else internally).

    Regards!

提交回复
热议问题