创建“新对象”与创建新对象之间的区别在于:和“类对象名称” [英] Difference between creating a "new object" and "Class objectname"
问题描述
例如,我有一个叫做Phone的类。
Say for example I have a class called Phone.
两者之间有什么区别?
Phone p;
和
Phone p = new Phone(200) //(200 is the price of the phone).
和
new Phone(200)
我已经在google上搜索甚至尝试过,但是可以
I've googled and even tried it on Eclipse but can't figure it out.
推荐答案
电话p;
仅声明一个引用处理程序 p
不会指向任何位置(它是未初始化的,除非您为其分配了某些内容,否则无法使用[感谢@Anthony])。
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 =新Phone(200);
声明引用处理程序 p
指向新创建的 Phone
对象(由 Phone(200)
初始化)。
Phone p = new Phone(200);
declares a reference handler p
which points to a newly created Phone
object (initialized with Phone(200)
).
新Phone(200)
创建一个新的 Phone
对象,但是由于没有引用
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).
(请注意,在Java中,所有类型为引用类型的变量实际上是引用处理程序。仅值类型的变量直接包含值。由于 Phone
是引用类型(它是类
),因此 Phone p
始终是对 Phone
的引用。)
(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
".)
这篇关于创建“新对象”与创建新对象之间的区别在于:和“类对象名称”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!