Solved

Please explain how to make a java class as Immutable?

Posted on 2011-03-20
14
321 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
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

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

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
factorial example challenge 10 62
mapShare challenge 13 68
best (free) software to access postgres db (java) 1 18
JAVA part two 5 41
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

758 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

18 Experts available now in Live!

Get 1:1 Help Now