I have seen that for initializing an object class we use constructor of the class or constructor of subclass of it.
like for a class Abc we use,
Abc object = new Abc()
;
LocalTime t = LocalTime.now();
System.out.println(t);
but here we are initializing object t of class LocalTime using LocalTime.now which is static function of class and object is returning that return value of that static method only. And new hasn't been used as well. Can we initialize any class object by using static method inside it? Please Explain.
CodePudding user response:
No, it's because LocalTime.now()
is designed to create an instance of LocalTime
. It will be calling the constructor internally.
Compare that with (say) Math.cos()
which returns a double
. That doesn't create an instance of java.lang.Math
.
Static methods which create (or at least return) instances of the type they're declared in are sometimes called factory methods. It's a pretty common pattern, but there's nothing about static methods that automatically creates an instance of the declaring type.
CodePudding user response:
Yes it is possibile to use static methods to create new objects. Generally to create a new instance using a static method you can do something similar to that:
public class MyClass {
public static MyClass createInstance() {
return new MyClass();
}
...
}
This approach is useful for some design pattern that creates objects under certain conditions. For example the singleton pattern that must ensure that there is only one instance for a particular class has an implementation that can be something similar to:
public class MySingleton {
private static MySingleton instance;
// A private constructor can not be called from outside that class
private MySingleton() {
}
public static MySingleton getInstance() {
if (instance == null) {
instance = new MySingleton();
}
return instance;
}
}
There are also other implementations for the singleton that can be more efficient or useful in different contexts (for example double check with synchronized block) but this is a simple and useful example to show how to use a static method to create instances of a class.
Other design patterns using a similar approach using a static method to create instances are:
- abstract factory
- factory method
- building
- double checked locking (a particular version of the singleton working in multithread environments)