0

I have a problem with one class in java

this class is public and extends of DefaultHandler all method of this class are public too ... but the variables are private...

My problem is that if I copy the value in other variable and modify this second variable the first change too.

is like static variables.. but they are no static... any idea!!!

thanks in advance

2
  • So cryptic. Can you explain in a little more detail and show us code? Commented Apr 24, 2011 at 2:02
  • 1
    Code example would help, IMO. Commented Apr 24, 2011 at 2:04

3 Answers 3

4

This is because you are actually modifying the same object. For instance, if you have

Object obj = new Object();

Object obj2 = obj;

You don't actually copy anything, you simply make obj2 "point" (not quite the right term, but it will work for now) to obj. Any changes to obj2 will be reflected in obj. Therefore, if you want to actually copy it, you need to physically create a new Object and then manually copy all of the values into the new creation. You could implement the prototype pattern to copy the object. Primitives don't behave this way so if you were to do the same thing with a double or an int for instance, it would behave the way you expect.

Does all of that make sense?

Sign up to request clarification or add additional context in comments.

Comments

0

You are probably having a problem with passing by reference versus passing by value. This page explains what I mean http://www.cs.umd.edu/class/sum2004/cmsc420/sum4v3e01/node6.html.

Comments

0

You probably are copying a reference to a changeable object, not the object itself; so after the copy, you have two references to the same object. Changing that object through either reference will have the same effect.

I can't tell you how to copy the actual object because there's no generic way to do it, but many classes provide a copy constructor or some other way to duplicate themselves. If you need help with that you'd have to provide more details.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.