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
What will be the default values of all the elements of an array defined as an instance variable?
Is an integer an object?
How is java created?
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.
what is difference between equals and ==?
What is a finally block? Is there a case when finally will not execute?
define polymorphism in java
How many types of flags are there?
How are observer and observable used in java programming?
Explain about public and private access specifiers?
Is java 1.7 the same as java 7?
What are the advantages of exception handling?
What is string and its types?
What is a conditional equation?
How many types of classes are there in java?