简体   繁体   English

java中的对象和引用

[英]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. **所以有三个引用( tsv ),尽管其中两个恰好引用了同一个对象。


* Of course, MyClass itself might create more objects internally. *当然, MyClass本身可能会在内部创建更多对象。

** Except in the case of primitive types, like int , float , etc. **除了原始类型的情况,如intfloat等。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM