can any one send me the example program of immutable class?

Answer Posted / jagannath

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



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What will be the default values of all the elements of an array defined as an instance variable?

571


Is an integer an object?

530


How is java created?

552


Draw a UML class diagram for the code fragment given below: public class StringApplet extends Applet { private Label sampleString; private Button showTheString; private ButtonHandler bHandler; private FlowLayout layout; public StringApplet() { sampleString = new Label(" "); showTheString = new Button (" Show the String"); bHandler = new ButtonHandler(); layout = new FlowLayout(); showTheString.addActionListener(bHandler); setLayout(layout); add(sampleString); add(showTheString); } class ButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { samplestring.setText("Good Morning"); } } } Note: The methods need not be indicated on the diagram.

1599


what is difference between equals and ==?

602






What is a finally block? Is there a case when finally will not execute?

559


define polymorphism in java

647


How many types of flags are there?

532


How are observer and observable used in java programming?

558


Explain about public and private access specifiers?

550


Is java 1.7 the same as java 7?

551


What are the advantages of exception handling?

572


What is string and its types?

629


What is a conditional equation?

570


How many types of classes are there in java?

535