/*
PointOne type objects has three members.
Two of type Integer and one of type ThreeD a custom class.
PointOneClone method takes an argument of PointOne type
and copy every value from his members to arguments members.
So the result is a PointOne instance with the exact same values
but any change we make to it does not affect the original
The last four printing methods gives the following results
class Copy_Constructor.PointOne
class Copy_Constructor.PointOne
true
false
So the last result means that i did not succed to make a clone.
How can i fix it ?
*/
import java.util.logging.Logger;
class ThreeD {
private Integer z;
public ThreeD(Integer newz) {
this.z = newz;
}
public int getz() {
return this.z;
}
public void setz(int newz) {
this.z = newz;
}
}
class PointOne {
private ThreeD threed;
private Integer x;
private Integer y;
public PointOne(ThreeD td, Integer x, Integer y) {
this.x = x;
this.y = y;
this.threed = td;
}
public PointOne PointOneClone(PointOne point) {
ThreeD td = new ThreeD(this.threed.getz());
return new PointOne(td, this.x, this.y);
}
public void setxy(int newx, int newy, int newz) {
this.x = newx;
this.y = newy;
this.threed.setz(newz);
}
public int getx() {
return this.x;
}
public int gety() {
return this.y;
}
public int getthreed() {
return this.threed.getz();
}
}
public class Copy_Constructor_For_Cloning {
public static void main(String[] args) {
ThreeD td = new ThreeD(4);
PointOne p1 = new PointOne(td, 2, 4);
PointOne p2 = null;
p2 = p1.PointOneClone(p2);
System.out.println("clonex :" + p2.getx());
System.out.println("cloney :" + p2.gety());
System.out.println("clone threed :" + p2.getthreed());
System.out.println();
System.out.println("originalx :" + p1.getx());
System.out.println("originaly :" + p1.gety());
System.out.println("original Tthreed :" + p1.getthreed());
System.out.println();
System.out.println("Setting new values : 10 , 20 , 30");
p2.setxy(10, 20, 30);
System.out.println("clonex new value is :" + p2.getx());
System.out.println("cloney new value is :" + p2.gety());
System.out.println("clone threed new value is :" + p2.getthreed());
System.out.println();
System.out.println("originalx is still :" + p1.getx());
System.out.println("originaly is still :" + p1.gety());
System.out.println("original threed is still :" + p1.getthreed());
System.out.println();
System.out.println(p1.getClass());
System.out.println(p2.getClass());
System.out.println(p2 != p1);
System.out.println(p1.equals(p2));
}
}
nikolaos 0 Newbie Poster
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster
nikolaos 0 Newbie Poster
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.