Reputation: 1
I noticed that the new
keyword is not used when creating the reference to the instance.
Here's the code snippet:
public class SingletonExample {
private static SingletonExample instance;
private SingletonExample() {
// Private constructor
System.out.println("SingletonExample instance created.");
}
public static SingletonExample getInstance() {
if (instance == null) {
instance = new SingletonExample();
}
return instance;
}
public void displayMessage() {
System.out.println("Hello from SingletonExample!");
}
public static void main(String[] args) {
// This won't work : SingletonExample instance = new SingletonExample();
// Getting an instance of SingletonExample using getInstance() method
SingletonExample singleton = SingletonExample.getInstance();
singleton.displayMessage();
}
}
I expected that creating a new instance of a class would involve using the new
keyword, but it appears that the getInstance()
method handles this without it.
I'm looking for an explanation of why the new
keyword is omitted in this scenario, and how the instance is actually created using the getInstance()
method.
Can someone provide insights into, how the getInstance()
method works in this context and why the new
keyword is not used?
Upvotes: 0
Views: 297
Reputation: 1
getInstance()
actually returns an instance of previously created and saved to a variable the instance of a class with the new
operator.
public static SingletonExample getInstance() {
if (instance == null) {
instance = new SingletonExample();
^^^
}
return instance;
}
The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor.
Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class. The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate.
The new operator returns a reference to the object it created. This reference is usually assigned to a variable of the appropriate type, like:
Point originOne = new Point(23, 94); The reference returned by the new operator does not have to be assigned to a variable. It can also be used directly in an expression. For example:
int height = new Rectangle().height; This statement will be discussed in the next section.
Upvotes: 2