can any one send me the example program of immutable class?
Answers were Sorted based on User's Feedback
public class ImmutableClass {
int i;
public ImmutableClass(int i)
{
this.i=i;
}
public int getI()
{
return i;
}
public ImmutableClass setI(int i)
{
if(i==this.i)
{
return this;
}
else
return new ImmutableClass(i);
}
public static void main(String args[])
{
ImmutableClass ic = new ImmutableClass(5);
ic.getI();
System.out.println(ic);
ic = ic.setI(10);
System.out.println(ic);
}
}
// If you pass 5 as the value in setter method, you will see
same address. It means whenever you are trying to change the
value of variable, a new object is created and returned. So
your object is immutable.
| Is This Answer Correct ? | 5 Yes | 2 No |
Answer / jinxuan
public class SingletonTest
{
public static void main(String[] args)
{
Singleton singleton = Singleton.getInstance();
Singleton singleton1 = Singleton.getInstance();
System.out.println(singleton == singleton1);
}
}
class Singleton
{
private static Singleton singleton = new Singleton();
private Singleton()
{
}
public static Singleton getInstance()
{
return singleton;
}
}
it means whenerver you new a Object,it returns the same
object address, i'ts Singleton Pattern. so your object is
immutable class
| Is This Answer Correct ? | 0 Yes | 3 No |
How do you bind variables?
Why stringbuilder is not thread safe?
How many techniques can be employed to create a string object?
What is a functional interface?
Where are variables stored?
which methods consisting of the serilizable interface?
which one is more efficient int x; 1. if(x==null) 2.if(null==x) state which one either 1 or 2?
Is java an open source?
Explain the difference between transient and volatile in java?
write a class to input 2 points by the user & check the line maked by the points is horizontal,vertical or rectangle?
Why does java doesnt suuport unsigned values?
Why singleton is not thread safe?