Reputation: 269
I was having a query that is if we have constructor in the class as below..
class A
{
A{}
}
Now what is the alternative to the constructors , I have gone for the approach that is static factory methods
class A
{
public staic A getinstance()
{
return new A();
}
}
In the above approch as per the analysis it will return immutable object but I have doubt on this analysis as the object that can be return with static factory method and can later be changed on , How to make it completely immutable..!! please advise..!!
Upvotes: 1
Views: 232
Reputation: 11875
Immutability is not related to the manner you create your objects. i.e. from constructors or factory methods.
JDK provides some ways to do this for Collections, using Collections.unmodifiableCollection
and related methods.
You can also incorporate it into your design, which becomes useful when working with concurrent applications.
A complete strategy for this is given here : http://docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html
Upvotes: 1
Reputation: 16158
alternative to the constructors : static factory methods
are not alternative to constructors. But you can have block intialization
which is equivalent to the constructors, but disadvantage is you can not pass arguments to it like :
class B {
private int i;
//intialization block, can not pass arguments like constructor
{
i=2;
}
//getter and setters
}
.
class A
{
public staic A getinstance()
{
return new A();
}
}
--> well this class will not return immutable object. To make class immutable, make class final, all members private and final, provide only getter methods and parameterised constructor. See below example :
final class A
{
final private int b;
public A(int b)
{
this.b = b;
}
public int getB() {
return this.b;
}
}
Upvotes: 0