Link to home
Start Free TrialLog in
Avatar of umaiyer
umaiyer

asked on

Clone

here is my problem.............

i have a class object created in different class.
in another class i want the same object to be returned .
i tried to do this using clone concept.
i am not getting the result what i expected.
i have a piece of code.
please guide me where i am going wrong & how to fix the same.

class Base extends Object implements Cloneable
{
     public void setCount(int count)
     {
     }
     public int getCount()
     {
          return 0 ;
     }
     public Object clone()
     {
          try
          {
               return super.clone() ;
          }
          catch(CloneNotSupportedException e)
          {
               return this ;
          }
     }
};

class TestClone extends Base
{
     int Count = 0 ;
     public TestClone()
     {
     }
     public TestClone(int data)
     {
          Count = Count + 1 ;
          setCount(Count) ;
     }
     public void setCount(int val)
     {
          Count = val ;
     }
     public int getCount()
     {
          return Count ;
     }
}

class Demo2
{
     public Demo2()
     {
          baseObj1 = new TestClone() ;
          baseObj = (Base)baseObj1.clone() ;

          int i = baseObj.getCount() ;
          System.out.println("clone value = " + i );
     }
     private Base baseObj = null  ;
     private Base baseObj1 = null ;
};

class DemoClone
{
     public static void main(String[] args)
     {
          baseObj = new TestClone(5) ;
          dm = new Demo2() ;
     }
     static private Base baseObj ;
     static private Demo2 dm ;
};

in my demo2 class i expect the output to displayed as 1.
because count would have been incremented by 1.

if this is wrong please guide me how to get the required output.

thanks in advance.

Avatar of Mick Barry
Mick Barry
Flag of Australia image

> because count would have been incremented by 1.

Why would you expect this, you do not call the ctor that increments count.
try this instead:

class Demo2
{
    public Demo2()
    {
         baseObj1 = new TestClone(0) ;
         baseObj = (Base)baseObj1.clone() ;

         int i = baseObj.getCount() ;
         System.out.println("clone value = " + i );
    }
    private Base baseObj = null  ;
    private Base baseObj1 = null ;
};
Avatar of umaiyer
umaiyer

ASKER

in my DemoClone class i am calling a ctor of TestClone & incrementing the Count to 1.
in demo2 class i do not want to increment count value.
Now i want to access this count value in my Demo2 class & i wants the value to get 1 .
how to acheive this.

The object you're printing the value of is a clone of baseObj1 which has not been increemented.
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial