这段代码中创建了多少个对象?

huangapple go评论74阅读模式
英文:

How many objects are created in this code?

问题

SurveyData newSurvey = new SurveyData(2);
SurveyData oldSurvey = new SurveyData();
SurveyData currentSurvey = oldSurvey;
oldSurvey = new SurveyData(5);       
newSurvey.setAges(0,45);
newSurvey.printAges();
英文:
SurveyData newSurvey = new SurveyData(2);
SurveyData oldSurvey = new SurveyData();
SurveyData currentSurvey = oldSurvey;
oldSurvey = new SurveyData(5);       
newSurvey.setAges(0,45);
newSurvey.printAges();

答案1

得分: 5

假设 SurveyData 的构造函数和对这些对象调用的其他方法不会在其中创建额外的对象,则答案是三。每次调用 new 运算符都会创建一个新对象。尽管 SurveyData currentSurvey = oldSurvey 是一个新的变量声明,但不会创建新对象。

英文:

Assuming that SurveyData's constructor and the other methods called on these objects don't create additional objects in them, the answer is three. Every call to the new operator creates a new object. Assigning SurveyData currentSurvey = oldSurvey does not create a new object, even though it's a new variable declaration.

答案2

得分: 3

SurveyData newSurvey = new SurveyData(2);
这行创建一个新对象,newSurvey 引用指向这个对象。

SurveyData oldSurvey = new SurveyData();
这行创建一个新对象,oldSurvey 引用指向这个对象。

SurveyData currentSurvey = oldSurvey;
这行不创建新对象。currentSurvey 引用指向与 oldSurvey 相同的对象。

oldSurvey = new SurveyData(5);
这行创建一个新对象。oldSurvey 引用现在指向这个新对象。

英文:
SurveyData newSurvey = new SurveyData(2);

this line crates a new object, and newSurvey reference points an object.

SurveyData oldSurvey = new SurveyData();

this line crates a new object, and oldSurvey reference points an object.

SurveyData currentSurvey = oldSurvey;

this line does not create an object. currentSurvey reference points the same object which oldSurvey points.

oldSurvey = new SurveyData(5);       

this line create a new object. Anymore oldSurvey reference points this new object.

You can see this process in the below image.

这段代码中创建了多少个对象?

huangapple
  • 本文由 发表于 2020年9月19日 02:52:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/63961313.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定