Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ever justified to have an object which has itself as a field? [closed]

Is it ever justified to have an object which has itself as a field like this :

class Thing {      Thing field;      public Thing() {         this.field = this;     } } 

I'm not talking about a class with a field of the same type but a class made so that every instance of the class has itself as a field. I just saw this in some legacy code (this field was never used) so I'm curious. Any legit use of this ?

like image 242
Autar Avatar asked Jul 27 '15 13:07

Autar


People also ask

Can an object be a field?

Yes, they can. anything can be a field.

Are Fields inherited in Java?

In the Java language, classes can be derived from other classes, thereby inheriting fields and methods from those classes.

What is a field in Java?

A field is a class, interface, or enum with an associated value. Methods in the java. lang. reflect. Field class can retrieve information about the field, such as its name, type, modifiers, and annotations.


1 Answers

Yes, though this is rare. This is used in the JDK for situations which the field could be this but it might not be.

From the class which implements Collections.synchronizedCollection(c)

static class SynchronizedCollection<E> implements Collection<E>, Serializable {     private static final long serialVersionUID = 3053995032091335093L;      final Collection<E> c;  // Backing Collection     final Object mutex;     // Object on which to synchronize      SynchronizedCollection(Collection<E> c) {         this.c = Objects.requireNonNull(c);         mutex = this;     }      SynchronizedCollection(Collection<E> c, Object mutex) {         this.c = Objects.requireNonNull(c);         this.mutex = Objects.requireNonNull(mutex);     } 

In this case the mutex might be the current class, however if this collection is obtained from an existing synchronised collection, the mutex might be different. e.g. if you call Map.values() and the Map is a synchronizedMap the mutex will be the map not the collection.


Another example is Throwable which points to itself as the cause by default.

/**  * The throwable that caused this throwable to get thrown, or null if this  * throwable was not caused by another throwable, or if the causative  * throwable is unknown.  If this field is equal to this throwable itself,  * it indicates that the cause of this throwable has not yet been  * initialized.  *  * @serial  * @since 1.4  */ private Throwable cause = this; 
like image 62
Peter Lawrey Avatar answered Sep 22 '22 21:09

Peter Lawrey