aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Clone problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Clone problem" Watch "Clone problem" New topic
Author

Clone problem

varinder mahajan
Ranch Hand

Joined: Jun 11, 2008
Posts: 47
class A implements Cloneable
{
int age;
A(int age)
{
this.age=age;
}
public int getage()
{
return age;
}
public Object clone()
{
A aa=null;
try
{
aa=(A)super.clone();

}
catch(Exception e)
{

}
finally
{
return aa;
}
}
public static void main(String str[])
{

A a1=new A(10);
A a2=(A)a1.clone();
System.out.println(a1.getage()+"==="+a2.getage());
System.out.println(a1.equals(a2));

}
}


output :

C:\>javac A.java
C:\>java A
10===10
false

expected output:

C:\>javac A.java
C:\>java A
10===10
true


Beat the world,if you can.......
Markus Klein
Greenhorn

Joined: Aug 29, 2008
Posts: 19
we have to know cloning for scjp?
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9321
    
  17

I don't think Clone class is in the objectives...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
varinder mahajan
Ranch Hand

Joined: Jun 11, 2008
Posts: 47
if it is not in the objective ..could any one explane it...
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9321
    
  17

as far as explanation goes, why do you expect to see true as the output?? You are calling super.clone in your clone implementation. The clone method of Object class will be called in that case. If you see the documentation of clone method in Object class, it says

While it is typically the case that:
x.clone().equals(x)
will be true, this is not an absolute requirement.


Since you are not overriding the equals method, so when you call equals, equals method of Object class is called. The equals method of object class looks for reference equality i.e. return this == other. Since the references are not equal, so it doesn't matter age field has the same value in both objects. You will get true if you use this code

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Clone problem