Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: To Make class immutable which has ref to other mutable objects

  1. #1
    Member
    Join Date
    Mar 2011
    Posts
    114
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default To Make class immutable which has ref to other mutable objects

    Ho to make a class immutable which has references to other objects which are mutable?
    Example for a class

    Public class Test
    {
    String abs;
    MyTest obj;
    int dfs;
    }


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,372
    Thanks
    183
    Thanked 836 Times in 779 Posts
    Blog Entries
    5

    Default Re: To Make class immutable which has ref to other mutable objects

    a) Encapsulate the fields by marking as private and use 'getter' methods b) Mark them as final c) mark the class as final d) If you are worried any client might change a field when it is returned (for instance, change the value(s) of a MyTest member) you can return a deep copy of this object.

Similar Threads

  1. [SOLVED] How to make a class be static if it's the main class.
    By javapenguin in forum What's Wrong With My Code?
    Replies: 18
    Last Post: January 10th, 2012, 05:14 AM
  2. immutable
    By saurabhRBMI in forum Java Theory & Questions
    Replies: 2
    Last Post: October 1st, 2011, 12:23 PM
  3. Replies: 3
    Last Post: July 24th, 2011, 07:13 AM
  4. instantiating class objects from an array
    By BadAnti in forum What's Wrong With My Code?
    Replies: 3
    Last Post: April 12th, 2011, 04:27 PM
  5. How to store objects from a class inn an array?
    By dironic88 in forum Object Oriented Programming
    Replies: 1
    Last Post: April 7th, 2011, 03:42 PM