[英]Object and references in java
I am confused as I am new to java, how many objects and references are created in the following piece of code? 我很困惑,因为我是java的新手,在下面的代码中创建了多少个对象和引用?
MyClass t = new MyClass();
MyClass s = new MyClass();
MyClass v = s;
Please explain the answer: 请解释一下答案:
2 Objects
3 References
A picture is worth more than a thousand words: 一张图片胜过千言万语:
An object is an instance of a class, created with new
. 对象是使用
new
创建的类的实例。 You use new
twice, so there are two objects. 你使用
new
两次,所以有两个对象。 * *
A variable is, generally speaking, a reference. 一般来说,变量是一个参考。 ** So there are three references (
t
, s
, v
), although two of them happen to refer to the same object. **所以有三个引用(
t
, s
, v
),尽管其中两个恰好引用了同一个对象。
MyClass
itself might create more objects internally.
MyClass
本身可能会在内部创建更多对象。
** Except in the case of primitive types, like int
, float
, etc. **除了原始类型的情况,如
int
, float
等。
2 Object and 2对象和
3 reference 3参考
if you do new
you are creating object so there are two new so simply two Objects 如果你做了
new
你就是在创建对象,所以有两个新的,所以只有两个对象
and if you define 如果你定义
Foo a;// you have just created a reference
* Note: new
is only a way to create object, it can be created using otherways too *注意:
new
只是创建对象的一种方式,也可以使用其他方式创建
So you are creating a new object and storing a reference to that object in t
. 所以你要创建一个新对象并在
t
存储对该对象的引用。 The same for s
. 同样的
s
。 Then you are assigning the s
reference to v
(not creating a new object). 然后,您将
s
引用分配给v
(不创建新对象)。 So you have three references and two objects. 所以你有三个引用和两个对象。
Actually, your answer is wrong. 实际上,你的回答是错误的。 It's the other way around:
反过来说:
2 objects (in the first two lines)
2个对象(前两行)
3 references (t, s, v, v and s share an object)
3个引用(t,s,v,v和s共享一个对象)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.