Why can I create an instance of a class without storing it to a variable and still have everything work?

梦想的初衷 提交于 2019-12-01 19:07:36

they are not static, so they need to be instantiated in order to be used, right?

Yes, but you are still instantiating the class with new ImplementHeaderButtons(), you just aren't storing a reference to that newly created instance anywhere.

You can still call a method on this instance as you have done in your example, but you will not be able to do anything else with it afterwards without a reference. Eventually the instance will be cleaned up by the garbage collector (provided the method you call does not store a reference to the object somewhere).

A variable is just a reference, for your convenience. You are not naming it, but it is just there, on the top of the stack (in general ;-) ). Do you can call it's methods as long as you can refer to the variable, either by using it's name (which you do not have) or by working on the "unnamed" object you've just created.

Your call to new ImplementHeaderButtons() returns an instance of ImplementHeaderButtons. Then, you call .Implement() on that instance.

Think of it like this:

(new ImplementHeaderButtons()).Implement(this, headerButtons);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!