Solved

Please explain how to make a java class as Immutable?

Posted on 2011-03-20
14
322 Views
Last Modified: 2012-05-11
Dear Experts,

Please give me an example, how to make a java class as Immutable,
0
Comment
Question by:haneef_nb
  • 4
  • 4
  • 2
  • +3
14 Comments
 
LVL 40

Expert Comment

by:gurvinder372
ID: 35178034
0
 
LVL 92

Expert Comment

by:objects
ID: 35178082
0
 
LVL 26

Expert Comment

by:dpearson
ID: 35178337
The basic pattern for making an immutable object is to make all the member data final.  You initialize the values in the constructor:

public class MyImmutableClass() {
     private final int m_Value1 ;
     private final int m_Value2 ;

     public MyImmmutableClass(int val1, int val2) {
        m_Value1 = val1 ;
        m_Value2 = val2 ;
     }

    public int getValue1() { return m_Value1; }
    public int getValue2() { return m_Value2; }
}

This class is "immutable" because once you create an instance of the class, it will never change.  When you call "getValue1()" you will *always* get the same value.

Turns out this is very useful in multi-threaded programming because you can share an immutable object among different threads without any problems - no need for synchronize or similar logic, because the object will never change once constructed.

They're usually used for relatively simple classes.  Some Java classes (like Date) should have been immutable, but aren't.  That's because when Date was first written we didn't really understand the importance of immutable classes.

Doug
0
 
LVL 4

Expert Comment

by:msk_apk
ID: 35179988
do not have set method.
have private fields.
have private constructor.
allow public get method.
0
 
LVL 1

Expert Comment

by:Shura85
ID: 35183240
If you are implementing/extending an existing Java class, such as ArrayList<T>, have any method that would alter the list throw an UnsupportedOperationException.  Since this is a runtime exception, it does not have to be declared in the method header, which gets around the inheritance issue.
0
 
LVL 1

Expert Comment

by:Shura85
ID: 35183286
Sorry if this comment is posted twice....got some bugs lately

@msk_apk
have private constructor

this does not affect the mutability of the list.  It's a step towards making it a singleton, but unless you define what will fill the list (and want it to be standard for all lists), its just a means of creation control.  The absence of setter methods + private fields make it immutable.  
0
 
LVL 4

Expert Comment

by:msk_apk
ID: 35186221
what you said is right.
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 

Author Comment

by:haneef_nb
ID: 35198355
Dear dpearson,

Thanks...

Ok, suppose my class has only setter methods, it doesn't have any final & private members, then can you please explain how can i prove that we can change the value further.  
0
 
LVL 40

Expert Comment

by:gurvinder372
ID: 35198401
since you have the setter methods, you can invoke them to change the value
0
 

Author Comment

by:haneef_nb
ID: 35198471
sorry sorry, not setters , i am having only getter methods in my class, then it is not a immutable
0
 
LVL 40

Expert Comment

by:gurvinder372
ID: 35198508
Yes, if there are no other methods also which can the object value, then the object becomes immutable.

Basically, even if the setter methods are there, all you have to make sure is that rather than making the changes in the current class (this variable), create a new object of the current class and return the same after setting the value
0
 

Author Comment

by:haneef_nb
ID: 35199247
Dear Experts,

see the below code snipet

public interface xxx
{
}

Please tell me how the jre knows it is a marker interface, and how a class which implements this interface , get special behavior

Please explain in brief..
0
 
LVL 40

Accepted Solution

by:
gurvinder372 earned 500 total points
ID: 35199309
there is no member variable inside, and their is no method declaration.

Actually, there is no need for the JVM to know if it is marker interface or not.

Only purpose of such an interface is for a program to find out if a class is implementing this interface or not. So, it just mark a class. For example, if your class implements clonable interface, it tells the JVM that this class implements clonable, so JVM treats that class as clonable
0
 

Author Closing Comment

by:haneef_nb
ID: 35376549
Thanks.......
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

867 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now