英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论