• 周日. 12 月 22nd, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

Java language anonymous object

King Wang

1 月 3, 2022

Anonymous object is a relatively fragmentary knowledge point , Although not the focus of the investigation , But I still think it’s necessary to mention .

Look at a piece of code :

new ClassName().Function();

In the code above , Create a new object directly , And called the Function function , But there is no reference to this object . You can probably see that , Anonymous objects are only for temporary use , And is recycled at the end of the statement . Actually in C/C++ There are similar operations in , such as for Indicator variables in the loop i:

for (int i = 0; i < length; i++) //i As a local variable , stay for It's eliminated at the end of the cycle
{
cout << i << endl;
}

An anonymous class The usage scenarios are as follows :

  • Method requires an object of a class as a parameter , And the object has no other use ;
  • The function of this object is just to call one of the methods at a time , There is no other use .
The above is right Java A rough introduction to anonymous objects , In general, let me tell you Java What is an anonymous object , What is the role . Specific content will be involved in the learning process in the future .

发表回复