Junior — Middle
Is it possible to instantiate an object without specifying a variable name?
sobes.tech AI
Answer from AI
Yes, in Java (and consequently in Android), it is possible to create an object without assigning it to a variable. Such an object is called anonymous and can be used, for example, to pass to a method or for one-time use.
Example:
new Button(context).setText("Click me");
Here, a Button object is created, and its setText method is called immediately, but the reference to the object is not stored in a variable.
Another example is anonymous classes or lambda expressions, where an object is created and used without a variable name.
However, if the object needs to be reused, it is better to store the reference in a variable.