Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

calling constructor

  Asked By: Ayden    Date: Nov 21    Category: Java    Views: 552

I am experiencing a problem trying to clone an object.
I have defined my own clone() method and I call it
from the methods in the class because I need to create
copies of the object and change them in certain ways.
In the clone method, I call the constructor of the
class, which changes certain variables in the object.
But the the new object is not the only one that ends
up with its variables changed--so does the old object
that instantiates the new object! Any idea why this



2 Answers Found

Answer #1    Answered By: Brent Brown     Answered On: Nov 21

one should not use the clone  method from within the class  itself. clone
is used when u want to create identical replicas of the same object  in
some other class not the same class. even though u may be able to do
that, it is not the right way of doing it.

there are cleaner ways of doing this. the problems u r facing could be
because u r passing references to ur constructor  inside clone method  and
when u modify the values of these references all the values are changed
in the new and the old object

try to avoid the clone stuff if this is what u want to accomplish.

Answer #2    Answered By: Cesara Fernandez     Answered On: Nov 21

I'm need something like this.
If i have a class

UserBean objUserBean = new UserBean();

--> UserBean has a getNumber() method

I need to work with it but in a general form like

Object obj = new UserBean();

--> i need obj.getNumber()

Some idea like the reflection, have any example to work with

Didn't find what you were looking for? Find more on calling constructor Or get search suggestion and latest updates.