In Effective Java its mentioned that "Unlike constructors static factory methods are not required to create a new object each time they're invoked".
class Car{
String color;
Boolean spoiler;
public Car(String s){
color=s;
spoiler = false;
}
public static Car redCar(){
return new Car("red");
}
}
In Main Class:
Car c2 = Car.redCar();
Car c3 = Car.redCar();
c2 and c3 are different objects. I did not get the context of "not required to create a new object each time invoked".
The static factory methods are methods that return an instance of the native class. The static factory method has names that clarify the code, unlike the constructors. In the static factory method, we do not need to create a new object upon each invocation i.e object can be cached and reused if required.
A factory method is nothing but a static method that returns an object of the class. The most common example of a factory method is getInstance() method of any Singleton class, which many of you have already used.
Advantage: -One advantages of static factory methods is that, unlike constructors, they have names. -A second advantages of static factory methods is that, unlike constructors, they are not equired to create a new object each time they're invoked. -They can return an object of any subtype of their return type.
The main disadvantage of static factories is that classes without public or protected constructors cannot be extended. But this might be actually a good thing in some cases because it encourages developers to favor composition over inheritance.
Because that's what you do:
public static Car redCar(){
return new Car("red");
}
// ^ here
If you want to return the same value you can do something like:
private static final Car RED_CAR = new Car("red");
public static Car redCar(){
return RED_CAR;
}
The point is that calling new Car()
will always return a new instance. Calling Car.newInstance()
means that the Car
class can decide what to do.
For example:
private static final Map<String, Car> CARS = new HashMap<>();
public static Car newInstance(final String colour){
return CARS.computeIfAbsent(colour, Car::new);
}
This uses the Car
constructor as a method reference to the new Map.computeIfAbsent
method, which calls it if a Car
of that colour is not already present in the Map
. This is a naive (not threadsafe) cache implementation.
So:
final Car one = Car.newInstance("red");
final Car two = Car.newInstance("red");
System.out.println(one == two) // true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With