Private Fields of Reference Type

Hi, today I stumbled upon a strange problem while wriring some java code.
There is a class with a private field of reference type, say an ArrayList. Now,what is the use of private fields? They are used so that they can not be modified from outside the class like public fields. General practice is to provide getter methods in the class to return the values of private fields.It goes fine with the primitive type variables and Strings(because Strings are immutable). But when the field is of reference type, we can still change its value.Have a look at the code:

import java.util.*;

class Aclass

private ArrayList list;
private String s= "My string";

public Aclass()
list= new ArrayList();

public ArrayList getList()
return list;

public String getString()
return s;

public class TestPrivate

public static void main(String args[])
Aclass ob= new a();
ArrayList alist= ob.getList();
ArrayList anotherList= ob.getList();

String s2= ob.getString();
String s3= ob.getString();

When you run this code,the output is:
[Hello, Hi]
My string
My string

You can see that content of list has been changed, but for string, they are not changed.So you can change the list object even if it is private.It is because the getList() method returns the reference to the same list object, so we can modify the list even if it is private.Now if you think that it is some loophole or bug of java,the you are wrong.It is just a simple basic concept of reference type variables.

Now, what should you do to avoid this thing. You have to modify the getList() method so that it returns the clone of list, not the actual list object.Here is the solution:

public ArrayList getList()
return (ArrayList) list.clone();

clone() will return the clone of object, not the actual list. Return type of clone() is Object, so we have to typecast it to ArrayList. Any modification done from the reference returned by this method will not change the actual one.For more information on clone() method,
go here.

, ,

  1. #1 by garima on February 13, 2010 - 6:49 PM

    hey..check this link this..will help you to enhance..your comp.. knowledge..and will also help you to solve probs..

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: