File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Clone problem

 
varinder mahajan
Ranch Hand
Posts: 47
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Markus Klein
Greenhorn
Posts: 19
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
we have to know cloning for scjp?
 
Ankit Garg
Sheriff
Posts: 9496
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't think Clone class is in the objectives...
 
varinder mahajan
Ranch Hand
Posts: 47
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if it is not in the objective ..could any one explane it...
 
Ankit Garg
Sheriff
Posts: 9496
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic