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

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

    Phone p; only declares a reference handler p which doesn't point anywhere (it is a not initialized and cannot be used until you assign something to it [thanks @Anthony]).

    Phone p = new Phone(200); declares a reference handler p which points to a newly created Phone object (initialized with Phone(200)).

    new Phone(200) creates a new Phone object, but since no reference to it is stored anywhere, it becomes immediately eligible for garbage collection (unless its constructor stores a reference somewhere, that is).

    (Note that in Java, all "variables" whose type is a reference-type are really reference handlers. Only variables of value-type contain values directly. Since Phone is a reference-type (it's a class), Phone p is always a "reference to a Phone".)

提交回复
热议问题