Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java member object inside class of same type

Tags:

java

oop

I am looking at a codebase and I often see something like:

public class SomeClass
{
 protected static SomeClass myObject;

 //...

 public static SomeClass getObject()
 {
  return myOjbect
 }
}

I'd like to make sure I understand the purpose behind this. Is it to ensure one instance of the class gets shared even if it is instantiated multiple times? I am not sure about the vocabulary here, or else I'd search for the answer, so if this pattern has a name, please let me know.

Also, this seems a little chicken-and-egg definition because the class includes an object of the type of the class. Why isn't this actually paradoxical?

Thanks!

like image 891
Gus Avatar asked Dec 09 '22 15:12

Gus


2 Answers

This is really only common with the Singleton Pattern where there is only this one instance of the class. While it has its uses, Singleton is over- and misused more often than not (usually to disguise procedural programming as OO). It also occurs very often in example code for Java AWT or Swing, where you typically subclass Frame / JFrame, and create an instance in a main method inside the same class.

Also, this seems a little chicken-and-egg definition because the class includes an object of the type of the class. Why isn't this actually paradoxical?

Why do you think it is? The class mainly describes what members instances of this type have - but a static member does not belong to an instance, it belongs to the class itself, so it doesn't have anything to do with the "blueprint" role of the class. Static members are really somewhat un-OO because of that.

But even on the instance level you can have references of the same type. For example, an entry in a linked list would typically have two references to the next and previous entries, which are of the same class.

like image 79
Michael Borgwardt Avatar answered Dec 13 '22 22:12

Michael Borgwardt


This is called the Singleton design pattern.

You are correct in stating that the purpose is to ensure only one instance of the class gets created.

Wikipedia has a preyty good article on the pattern.

like image 37
jjnguy Avatar answered Dec 13 '22 23:12

jjnguy