• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Rob Spoor
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Junilu Lacar
  • Tim Cooke
Saloon Keepers:
  • Tim Holloway
  • Piet Souris
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Frits Walraven
  • Himai Minh

What are Anonymous objects exactly ?

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have a question concerning anonymous object in Java.

Is an anonymous object an object that has no explicit nor implicit one. Or is it an object that has no explicit reference but it can have an implicit one (e.g a method paramter)

The following example to illustrates what I mean ::

 
isam alie
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
My question is : Is the object created in line 13 an anonymous object ? if so why ?
 
Sheriff
Posts: 16578
277
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
No it's not, because you know exactly what class it is: Circle. Just because there's no explicit reference that you can use to call other methods with the same instance, that doesn't make it anonymous. It's still an instance of the Circle class itself.

This is how you create and use an anonymous class:

The class created on the right side of the assignment is anonymous because it is not named. It's not a Circle per se but rather it's a subclass of Circle. It can't be reused because there's no way to reference it except through a Circle reference, in which case the compiler will not allow you to call the circumference() method. You have to make the call to the circumference() method provided by this anonymous subclass in the same statement that it has been defined.
   
 
Marshal
Posts: 73766
332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Your equals() method. I am afraid, is written incorrectly. It should override this method, and should be accompanied by an overridden hashCode() method. Because of the difficulty testing equality with certain double values, I suggest the following is what you need.Or something similar. Yes, you do need a second pair of () around the cast, which cannot fail after instanceof and &&. The behaviour of instanceof means you don't need a separate test for nulls. Yes, you can still make those methods go wrong if you create any subtypes of Circle.

Anonymous object isn't a very accurate name; it refers to any object passed to something rather than being assigned to a reference. Yes, the 15 circle could be called an anonynous object, but I prefer not to use that term.
 
Campbell Ritchie
Marshal
Posts: 73766
332
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Are we confusing anonyous classes and anonymous objects, the latter being a poor term which should never have been coined?
 
Junilu Lacar
Sheriff
Posts: 16578
277
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
@OP: I'm not sure the way you're using "explicit" vs "implicit" is helping you get more clarity around these concepts although I understand what you mean when you use those terms. When you say "implicit reference," you mean it's an object reference that isn't assigned to a variable that can be used multiple times.

When you're thinking about anonymous classes, it's better to contrast that with named classes, not "explicit" classes.

In your example, Circle is the named class and the expression new Circle(5) yields a reference to a Circle object with a radius of 5. It's not anonymous because you know the exact class of this object, Circle.

This code I gave defines an unnamed/anonymous subclass of Circle which defines a new method, circumference(). That class is also instantiated at the same time and the resulting object reference immediately used to invoke the circumference() method. You could capture a reference to this anonymous object in a variable but that variable can only be declared as a Circle, not whatever subclass it is you've just defined. Therefore, even if you capture it, you still wouldn't be able to use the new circumference() method defined by the anonymous class.

I hope this hasn't confused you even more.
 
Junilu Lacar
Sheriff
Posts: 16578
277
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:Are we confusing anonyous classes and anonymous objects, the latter being a poor term which should never have been coined?


I agree, the term "anonymous object" can create a lot of confusion especially since an anonymous class defined and used the way I showed it is also an anonymous object. However, if you capture the reference to a variable, that object is no longer technical "anonymous" because you can reference it by name. It's just that name doesn't allow it to be treated as an instance of the anonymous class but rather as an instance of the base class. Clear as mud yet?
 
Junilu Lacar
Sheriff
Posts: 16578
277
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You can actually see what class name the JVM assigns to the anonymous class:

In the above code, it's the {} that comes after new Circle(5) that makes it an anonymous class definition as well rather than just a new instance of the Circle class.
 
isam alie
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:Are we confusing anonyous classes and anonymous objects, the latter being a poor term which should never have been coined?



I am referring to anonymous objects here.

To my understanding: an anonymous is an object that its reference has not been assigned explicitly ( using an direct assignment statement) to a reference variable. But its reference can be assigned implicitly (by passing it to a method parameter).
Or for an object to be anonymous it has be nameless (no reference variable refers to it)

which one is correct ?

And am I understanding right ? or Am I missing something ?  
 
Bartender
Posts: 1064
33
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In other languages, an object that gets created and immediately passed to another method or has a method called on it is frequently called an "anonymous temporary (object)".

The folks around here seem not to like or use that term much, but when working on C/C++ we used the term all the time.

Your description of "anonymous object" matches well with what we called anonymous temporaries, or sometimes anonymous temporary objects.

You don't have a concept of "anonymous classes" in the other languages that we frequently use the term in.
It is easy to confuse anonymous classes with anonymous objects in Java, perhaps that is why they avoid the term.
 
Junilu Lacar
Sheriff
Posts: 16578
277
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
As far as I can tell, the Java Tutorials and the Java Language Specification only reference "anonymous classes"—with a quick Google search, I don't see any links to trusted Java reference materials that refer to "anonymous object."

@OP: please cite your sources where you found the term "anonymous object."
 
isam alie
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Junilu Lacar wrote:As far as I can tell, the Java Tutorials and the Java Language Specification only reference "anonymous classes"—with a quick Google search, I don't see any links to trusted Java reference materials that refer to "anonymous object."

@OP: please cite your sources where you found the term "anonymous object."



From: Introduction to Java Programming and Data Structures, Comprehensive Version by Y. Daniel Liang

Usually you create an object and assign it to a variable, then later you can use the variable
to reference the object. Occasionally, an object does not need to be referenced later. In this
case, you can create an object without explicitly assigning it to a variable using the syntax:
new Circle();
or
System.out.println("Area is " + new Circle(5).getArea());
The former statement creates a Circle object. The latter creates a Circle object and
invokes its getArea method to return its area. An object created in this way is known
as an anonymous object.

Also : printArray(new int[]{3, 1, 2, 6, 4, 2});
The preceding statement creates an array using the following syntax:
new elementType[]{value0, value1, ..., valuek};
There is no explicit reference variable for the array. Such array is called an anonymous
array.

Also mentioned in the book that an object that is not referenced by an reference variable is known as "garbage". So is the term "garbage" would be better to use instead of anonymous object to describe an object that is not referenced by any reference variable to not confuse anonymous objects with anonymous classes ?
 
Junilu Lacar
Sheriff
Posts: 16578
277
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

isam alie wrote:
Also mentioned in the book that an object that is not referenced by an reference variable is known as "garbage". So is the term "garbage" would be better to use instead of anonymous object to describe an object that is not referenced by any reference variable to not confuse anonymous objects with anonymous classes ?


The term "garbage" is in reference to garbage collection. Since you're not holding on to the object reference, the object created in such a manner is immediately eligible for garbage collection after it has been used. It's not good to use the term "garbage" in any other context. That will just create more confusion, in my opinion.
 
Junilu Lacar
Sheriff
Posts: 16578
277
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

isam alie wrote:
From: Introduction to Java Programming and Data Structures, Comprehensive Version by Y. Daniel Liang

Usually you create an object and assign it to a variable, then later you can use the variable
to reference the object. Occasionally, an object does not need to be referenced later. In this
case, you can create an object without explicitly assigning it to a variable using the syntax:
new Circle();
or
System.out.println("Area is " + new Circle(5).getArea());
The former statement creates a Circle object. The latter creates a Circle object and
invokes its getArea method to return its area. An object created in this way is known
as an anonymous object.


The problem I have with this definition is that it creates confusion with the concept of anonymous classes. The code may look similar but the effect is NOT the same as creating an anonymous class. The code in that book is NOT creating an anonymous class, it's just creating a one-time use instance of Circle. There's not an entirely new class created there. Compare that with this:

With this code, you ARE creating an entirely new class, instantiating it and invoking a method on it. So that is both an anonymous class and an unreferenced/unnamed object (aka "anonymous object").
 
Jesse Silverman
Bartender
Posts: 1064
33
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
All or most of my experience with the term "anonymous (temporary) objects" (which is a lot) is generally outside of Java.

I see "anonymous array" as a term in the Index for the Sybex 815 OCP 11 book by J & B, but can't find it in the text itself.

I have seen some use of that term in reference to something like

result = takesArray( new Int[5] );

even in Java, but rarely.

I suspect this is a case of a multi-lingual author borrowing a phrase commonly used in one or more other languages and applying it to Java.

I would have done so too, for the same reasons, but would now avoid it in Java-centric discussions, because anonymous classes are a very popular Java feature and the term simply isn't used in the authoritative Java literature (I knew I hadn't seen it, but not that an exhaustive search would turn up empty).

I wouldn't call them garbage, because whatever method they are passed to could stick them somewhere rather than just looking at them, if they do, they will NOT be available for garbage collection.

For the most part if someone says:
new SomeClass().someMethod();

the object would indeed usually be eligible for garbage collection upon termination of someMethod(), I don't know the best term that doesn't have anonymous in it, but I might call it a temporary that will be eligible for garbage collection upon completion of the method.
 
Junilu Lacar
Sheriff
Posts: 16578
277
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here's a different use of an anonymous class/object.

Let's go with your Circle class and say it has a draw() method with fairly complicated logic in there:

Say you had another class, ShapeRenderer, that interacted with Circle objects and you wanted to test that interaction. You only want to check that the Circle.draw() method is being called a certain number of times but you don't want to actually draw the Circle objects during your tests. To get around that, you can stub out the draw() method using an anonymous class, like so:

Lines 5-10 defines an anonymous subclass of Circle. An instance of the subclass is also created and a reference to it assigned to the circleFixture variable. Notice that you can only declare that variable to have type Circle because the actual class is anonymous. The object's reference, however, is now saved in a variable, so it's hard to argue that it's still anonymous at this point. This is kind of why the term "anonymous object" is tricky at best—you have to be very clear on what the difference is between "class" and "object" in this context and which one of them is actually the anonymous one.
 
Junilu Lacar
Sheriff
Posts: 16578
277
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Jesse Silverman wrote:I don't know the best term that doesn't have anonymous in it, but I might call it a temporary that will be eligible for garbage collection upon completion of the method.


Yeah, that's quite a mouthful. How about a "one-off instance"?
 
Campbell Ritchie
Marshal
Posts: 73766
332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Junilu Lacar wrote:. . . . How about a "one-off instance"?

All is well until you change the methoid you are passing the newly created object to.From here, the right ends of both statements look the same; I have even mis‑indented the code to make that fact more obvious.. But what is on the left does something completely different.
 
Jesse Silverman
Bartender
Posts: 1064
33
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In other languages, without anonymous classes, the term "anonymous temporary object" is very common usage, as are pure rvalues (well, in C++).

I will defer to whatever gets adopted by this thread and try to use that whenever the concept comes up in discussions about Java.

We are in full agreement that "garbage" is a terrible replacement, tho.
 
Junilu Lacar
Sheriff
Posts: 16578
277
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:All is well until you change the methoid you are passing the newly created object to.


True, the only thing I can think of now is "unnamed reference" but then again, it does get assigned a name when you pass it in as an argument to a method call.
 
Junilu Lacar
Sheriff
Posts: 16578
277
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Jesse Silverman wrote:I will defer to whatever gets adopted by this thread and try to use that whenever the concept comes up in discussions about Java.


We're just chatting, it's not like we can issue an edict banning the use of "anonymous object" or anything like that. Deferring to any consensus we come to here, while a nice gesture that's appreciated, isn't really going to get you much outside of this thread.
 
isam alie
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Jesse Silverman wrote:

I suspect this is a case of a multi-lingual author borrowing a phrase commonly used in one or more other languages and applying it to Java.



You are right. Laing has a C++ book. He does mention anonymous objects in it as follows :

Usually you create a named object and later access its members through its name. Occasionally you may create an object and use it only once. In this case, you don’t have to name it.
Such objects are called anonymous objects.
 
Junilu Lacar
Sheriff
Posts: 16578
277
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

isam alie wrote:

My question is : Is the object created in line 13 an anonymous object ? if so why ?


Now that we're a little bit clearer on what you mean by that term, I guess the answer would be yes, it is anonymous in that particular usage on line 13. Note that to Campbell's recent point, however, once you dig down into the Circle.equals() method and follow the path the reference takes, it will no longer be anonymous because the object reference will be assigned to a parameter which of course has a name.
 
isam alie
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Junilu Lacar wrote:
however, once you dig down into the Circle.equals() method and follow the path the reference takes, it will no longer be anonymous because the object reference will be assigned to a parameter which of course has a name.




But it will be nameless (anonymous) once again once the equals method is finished (as it will be popped from the call stack) and returns control back the the main method. Won't it ?
 
Jesse Silverman
Bartender
Posts: 1064
33
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

isam alie wrote:

Junilu Lacar wrote:
however, once you dig down into the Circle.equals() method and follow the path the reference takes, it will no longer be anonymous because the object reference will be assigned to a parameter which of course has a name.




But it will be nameless (anonymous) once again once the equals method is finished (as it will be popped from the call stack) and returns control back the the main method. Won't it ?

Here yes, but it is quite possible to pass it into some other method besides equals, that will for example, add the reference to some collection object.
There will still be no way to refer to that object by name yet, but it will not be garbage and would remain accessible via. say, arrayListOfShapes.get(36) or something.

EDIT -- to be more explicit -- so, sure, it will still be anonymous, but that does NOT mean it is garbage collected after, as the method you passed your "one off" anonymous instance to can pretty easily squirrel it away somewhere for later enjoyment.
 
isam alie
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Jesse Silverman wrote:

isam alie wrote:

Junilu Lacar wrote:

EDIT -- to be more explicit -- so, sure, it will still be anonymous, but that does NOT mean it is garbage collected after, as the method you passed your "one off" anonymous instance to can pretty easily squirrel it away somewhere for later enjoyment.





Why would it be anonymous if the method stored the object reference say in an ArrayList ? then the passed Circle Object will be accessible via an ArrayList indexed variable.  

 
Jesse Silverman
Bartender
Posts: 1064
33
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

isam alie wrote:

Why would it be anonymous if the method stored the object reference say in an ArrayList ? then the passed Circle Object will be accessible via an ArrayList indexed variable.  



It will be accessible via. that ArrayList indexed variable, but it is not a given that this ArrayList will be in scope of the method that made the call, a little subtle, but sometimes important.
The method you call could have access to places/data your code itself doesn't have direct access to.
 
Junilu Lacar
Sheriff
Posts: 16578
277
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This has turned out to be a pretty long thread, much longer than I'd expect to see around a discussion about "anonymous."

In the grand scheme of things, does it really matter? I'd say the important things to understand are:
1. What are anonymous classes in Java and what are they typically used for. You already have some pretty good examples of this.

2. What are the difference between these statements:


3. Use the term "anonymous object" very carefully when talking about Java code. There are many ways you can interpret that phrase.

Other than that, the rest of the discussion is mostly about semantics. Honestly, that's not too interesting and I wouldn't overthink it if I were you. There are better things to expend your time and effort on.
 
Jesse Silverman
Bartender
Posts: 1064
33
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Junilu Lacar wrote:This has turned out to be a pretty long thread, much longer than I'd expect to see around a discussion about "anonymous."

In the grand scheme of things, does it really matter?

3. Use the term "anonymous object" very carefully when talking about Java code. There are many ways you can interpret that phrase.

Other than that, the rest of the discussion is mostly about semantics. Honestly, that's not too interesting and I wouldn't overthink it if I were you. There are better things to expend your time and effort on.



Agreed.  It is a huge deal in C++, because of RValues and "Move Semantics".
In a garbage collected language without move semantics, like Java, it is all hair-splitting, it doesn't make any meaningful difference.
I was looking for the proper term in Java, but it is simply a distinction from C++ that Java doesn't particularly care about at all, and really doesn't have a term for that appears in the JLS or anywhere else important, but might be mentioned by C++ people when doing Java, out of habit more than anything else.
 
Jesse Silverman
Bartender
Posts: 1064
33
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Just a note, this notion of what some call anonymous temporary objects came up spontaneously in another thread on this forum as part of a general discussion.  I was not involved.
Some of what I mentioned in this thread was explained there as well, most importantly that the method called with such might store a reference to it somewhere.
 
Jesse Silverman
Bartender
Posts: 1064
33
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When studying "Try With Resources" using IOStreams type objects which very often wrap each other, you actually see anonymous objects extremely, extremely commonly.
I've watched a few presentations, none use either the term "anonymous object" nor any other, they just use them all over the place.  There is no common term in Java.

You will see them extremely frequently in "Try With Resources", because while you CAN write:


It is far more common to see:


Note that using this style there is no way to directly make use of the FileReader, but nobody cares because we only interact with it thru the BufferedReader which wraps it anyway.

So Java makes reasonably frequent use of what C/C++ call anonymous temporary objects, but because it is garbage collected and there are no "Move Semantics" nobody cares enough about what they are to bother giving them a name.  They still appear all the time in a number of idioms, most commonly wrapped IOStream or Reader/Writer objects.

 
Jesse Silverman
Bartender
Posts: 1064
33
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I just remembered one more place they are ridiculously common, whatever you call them.

The Exception objects that get thrown from code are probably more often anonymous than not:



No name for a reference supplied or needed.
 
Junilu Lacar
Sheriff
Posts: 16578
277
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Jesse Silverman wrote:The Exception objects that get thrown from code are probably more often anonymous than not:


No, that's not right. An unreferenced object is not the same as an anonymous one. The exception object created with that code still has a named class: java.lang.ArithmeticException.

Here's the difference:

That will give you this result:

java.lang.ArithmeticException
Main$1

See it for yourself here: https://replit.com/@jlacar/AnonymousConstructor#Main.java
 
Jesse Silverman
Bartender
Posts: 1064
33
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

No, that's not right. An unreferenced object is not the same as an anonymous one. The exception object created with that code still has a named class: java.lang.ArithmeticException.



So back to my point on deferring to the Forum's chosen terminology, which I will do.

C/C++ doesn't deal with Anonymous Class types, and often cares very much about whether things are RValues or not.

Java does have Anonymous Classes and never cares about whether things are RValues or not.  I note that "lvalue" appears a total of exactly one time in the JLS, to mention that it is a term that C uses.  They omitted C++.  The term Rvalue literally never appears in the JLS even once.

When speaking about Java, I will only refer to "unreferenced objects" and not use the terms from other languages.
I find the term less than ideal, because there is often a reference somewhere, in the first case stored inside the wrapping object, and in the second case managed by the VM as it unwinds the call stack to try to find some code to handle the Throwable/Exception, but it can't be referenced directly in the source code creating it, so fine, I will always call it "unreferenced".
I will note my minor complaint that this complicates the simple phrasing "All unreferenced objects are eligible for garbage collection" but so be it.

Cheers!

 
Junilu Lacar
Sheriff
Posts: 16578
277
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Jesse Silverman wrote:I find the term less than ideal, because there is often a reference somewhere, in the first case stored inside the wrapping object, and in the second case managed by the VM as it unwinds the call stack to try to find some code to handle the Throwable/Exception, but it can't be referenced directly in the source code creating it, so fine, I will always call it "unreferenced".


Well, you're right to say that the exception objects in the code example are NOT unreferenced because they are referenced by the List object created by the List.of() method. Note that the comments I put there only talk about the objects being anonymous or not. I didn't say anything about being unreferenced or referenced.

If anything is unreferenced in that example I gave, it's the List object itself. That takes us back to it being a "one-time-use use-in-place" reference. So there is a somewhat fine line that differentiates an unreferenced instance of a named class from an unreferenced instance of an anonymous class.
 
Jesse Silverman
Bartender
Posts: 1064
33
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Junilu Lacar wrote:

Jesse Silverman wrote:I find the term less than ideal, because there is often a reference somewhere, in the first case stored inside the wrapping object, and in the second case managed by the VM as it unwinds the call stack to try to find some code to handle the Throwable/Exception, but it can't be referenced directly in the source code creating it, so fine, I will always call it "unreferenced".


Well, you're right to say that the exception objects in the code example are NOT unreferenced because they are referenced by the List object created by the List.of() method. Note that the comments I put there only talk about the objects being anonymous or not. I didn't say anything about being unreferenced or referenced.

If anything is unreferenced in that example I gave, it's the List object itself. That takes us back to it being a "one-time-use use-in-place" reference. So there is a somewhat fine line that differentiates an unreferenced instance of a named class from an unreferenced instance of an anonymous class.



Ah, I was just still fumbling about for a go-to term for things like my sample instances of:
new FileReader("myFile.txt")
and
new ArithmeticException()

(taken from actual code samples seen dozens of times over the last day and a half of Java review)

In C++ I just call them anonymous temporaries or anonymous objects, but we agree that is a terrible term to use on Planet Java.  I will stop doing that.

I guess I am happy to say "one-time-use use-in-place" objects, despite it not being strictly true, if it ends the Cheese Shop experience of terminology protocol negotiation.
My point was whatever we do call them, they are certainly not rare in Java, it is only that there aren't very important reasons to "refer" to them with any special term, as the distinctions which are important in C/C++ are literally non-existent in Java, except perhaps possibly to the optimizer when deciding to place something on the stack in preference to the heap, invisibly to the programmer.

Perhaps not having a term for them in Java helps underscore the fact that the distinction is simply irrelevant to all Java application programmers, and, in fact, the JLS.  Here it is "a distinction without a difference".
 
Jesse Silverman
Bartender
Posts: 1064
33
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Another place we see these, whatever it is best to call them.

In the famous description of "How do I create an instance of an inner class from outside the outer class?" which I find one of the trickier bits of syntax in classical Java:



Is a bit tricky to understand.  Here we are creating a new instance of OuterClass, keeping no explicit reference to it, but then using that to create an instance of the InnerClass using this very weird syntax.  The InnerClass itself holds a reference to the outer class.  Even once the syntax is mastered, this is a little bit of a complex situation.

The OuterClass instance that is being kept alive by our InnerClass instance referenced by innerObj has no direct reference from outside.  It is not garbage while innerObj remains in scope, or any other reference to that InnerClass instance remains in scope.  We have no direct way to reference OuterClass methods or data, but it is alive in our program.  InnerClass methods that we *can* call may be making calls to OuterClass methods on this OuterClass instance.

I was thinking of this as well when I said there are many places this happened, but I had no reference to the instance until I thought of it explicitly now.

I don't know how often this happens in real life, but we see it in just about every InnerClass tutorial in existence.  OuterClass certainly isn't unreferenced, and I want to call it anonymous, because I can't directly name it.  Names with "one-off" seem inappropriate because the InnerClass reference may not be short-lived, and thus the OuterClass reference is alive until whenever that goes away, no?

Apparently I can't let this go in some interesting metaphysical parallel.
 
Junilu Lacar
Sheriff
Posts: 16578
277
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Jesse Silverman wrote:whatever it is best to call them.


The JLS calls them "Class Instance Creation Expressions" - https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-ClassInstanceCreationExpression. Its value is a reference to the object that was created and as such, it can either be used in place or assigned to a reference variable for use elsewhere, potentially multiple times. If you choose to use the reference in place without assigning it to anything, then the object will become eligible for garbage collection immediately after the reference is used. This is the "one-time use" use case.

Anonymous classes are explained pretty well in the Tutorials: https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html

The examples given in the tutorial show that there's a difference between an instance of an anonymous class and an object reference that is not assigned to a reference variable.

The class declared on line 10 is obviously not an anonymous class.

Two anonymous classes are declared: one on line 23 and another on line 34. Everything after the = operator up to the closing brace on lines 32 and 43 respectively constitutes a Class Instance Creation Expression as well which means an anonymous class declaration is also a Class Instance Creation Expression. You can verify that from the first sentence here: https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.9.5

The references to the instances of these anonymous classes are not, however, "one-time use" references. They are assigned to the frenchGreeting and spanishGreeting reference variables, respectively.

I hope this helps you in your quest for the proper names to use for these things.
 
Jesse Silverman
Bartender
Posts: 1064
33
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I often go off into the wild, either YouTube videos or random Java blogs on the Interwebs, then come back here reporting if they seem confused and have managed to get me confused, or if they have something interesting in them I don't see in the forum or places normally referenced by forum posters.

Sometimes I am stressing about inconsistent or ambiguous use of terms that are being taught to many people who already are or intend to be doing Java for a living.  This will make it harder to communicate with them in the workplace or on open source projects.

I noted that Jeanne and Scott's book contain the term "Anonymous Array" (or arrays, I forget) in the index, but I couldn't find the reference in the text.
Perhaps because it was anonymous.

People doing (or teaching) Java for a living definitely use the term "Anonymous Array".
I am aware the term never occurs in the Java SE 16 version of the JLS, because I looked.

Home slice here teaches Java for a living, including in this video:
https://www.youtube.com/watch?v=RyfrW3h8o9s

I don't know what this person calls them in the other language used in this video, but in English they are called "Anonymous Arrays" each time they are mentioned...
This video is in about 50% English (that is, about 90% of the sentences are in 50% English).
I have found myself occasionally watching them and understanding them from the 50%:
https://www.youtube.com/watch?v=389Zd7aqgGo

This one is about 33% or so English, but all the Java Terms are in English, including "Anonymous Array":
https://www.youtube.com/watch?v=lk_qgV-GlYk

100% English (he also uses the term "Anonymous Object")  He commits the Sin of "Bad Indentation" and writes arrays like int name[] (which is terrible too)
but the Java is otherwise solid:
https://www.youtube.com/watch?v=apg5KvSnA5U

60% English:
https://www.youtube.com/watch?v=cHdnlCF0e7Y

60% English, 40% Bangla:
https://www.youtube.com/watch?v=Ev6DdTXyW8Y

100% English (also writes arrays with C syntax int x[] ):
https://www.youtube.com/watch?v=sJTYZLfdSF4

OK, so the term "anonymous array" is in wide use even among people who are Java-centric or mono-lingual Java users.

The original question was about "anonymous objects" which I attested was a commonly used term I would need a good replacement for to be able to stop saying.
Quite literally people all over the world are using the term, many of whom teach Java for a living or are primarily or even full-time Java people...

"Hello, Aliens!" this dude has 1.4M subscribers.  That's a lot.
He doesn't just use "Anonymous Array" here, but "Anonymous Object" like I do...:
https://www.youtube.com/watch?v=AmRjm4Cksmo

100.00% English reference to "Anonymous Object" from BroCode (very cool GUI stuff!):
https://www.youtube.com/watch?v=u_BZlRodfVU

Less exciting:
https://www.youtube.com/watch?v=HnrOve6p63Y

Arabic, English, Java.  Learn how to say "Anonymous Object" in Arabic:
https://www.youtube.com/watch?v=WtDSxH2MG8I

All English, "Anonymous Object" (he also says "nameless object" twice):
https://www.youtube.com/watch?v=MaV2ZPI2Dlg

10% English, but Java and "Anonymous Object" are part of that 10%:
https://www.youtube.com/watch?v=3paGtMMf9sw

Also 10% English, but featuring the words "Anonymous Object":
https://www.youtube.com/watch?v=MIU1J4oGxrQ

100% English, presents "Anonymous Object" as a totally normal term:
https://www.youtube.com/watch?v=m1IeoroPfzs

90% Hindi:
https://www.youtube.com/watch?v=iK-rFEpbFGw

Bengali:
https://www.youtube.com/watch?v=3qjJJtevVGQ

Egyptian Arabic:
https://www.youtube.com/watch?v=D8R1HFTDNj4

AP Computer Science Teacher (USA):
https://www.youtube.com/watch?v=M3txaGluqqY

I believe this is 92% Turkish, but I can still follow it and he says "Anonymous Object" in English every time:
https://www.youtube.com/watch?v=jokGThigBk8

I can't tell what language this guy is speaking in 90% of the video, but both "Anonymous Class" and "Anonymous Object" are pronounced at the appropriate points in the video:
https://www.youtube.com/watch?v=9LR12nz5dMw
The script they use in that language is very pretty.
I avoided videos where they had any anonymous classes except this last one.

Conclusion: The term "Anonymous Object" (very rarely, "Nameless Object") is indeed in very common use in the way that the OP and myself were using it.
I will adhere to local custom at the Ranch if we collectively decide we prefer to call them "Nameless Object", "Spud" or "Moose Turd" but plenty of people all across the planet are using the term "Anonymous Object" in English to describe exactly that.
 
Jesse Silverman
Bartender
Posts: 1064
33
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I found so many examples of use of the disparaged term from around the globe that you posted first!

So, the preferred term, if we wish to be consistent with the JLS is: "Class Instance Creation Expressions".

While that sounds more descriptive than "spud" or "moose turd", it seems unsatisfying as an appellation for the created object itself over its potentially long lifecycle.

The expression creates them, great, that's what I would call the expression that creates them, ok, good...

but people are using the term to describe the objects living and breathing out in java heap land that have no names.

Sure, the example I gave of the new GoodNameNotFoundException() only lives from the throw to wherever it eventually gets caught.

But the others can live quite some time.

It is sad enough they have no names as individuals.

I want one name we can use collectively for them.

I have shown that "Anonymous Object" is in extremely wide use, I think I counted five or six languages presenting that term in a Java context in the way I used it.
"Nameless Object" might be harder to accidentally confuse with "Instance of Anonymous Class" so might be preferable (the term is in much less common use).

Sure, they are magically born from invocations of "Class Instance Creation Expressions" but can be running around doing things for potentially quite some time after the spell is cast.

I will attempt to add "Class Instance Creation Expression" into my working vocabulary, but reject the term as a name for nameless objects thru-out their lifecycle.
 
Blueberry pie is best when it is firm and you can hold in your hand. Smell it. And smell this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic