Learn Spring Step By Step
http://www.java4s.com/spring/
Keep watching the blog and share the information........
public
class Person {
private Car car;
private String name;
public Person(Car c, String n) {
car = c;
name = n;
}
public Person(Person p)
{
name = p.name;
car = new Car(p.car);
// we assume we have a copy
//constructor for Car
}
public String toString() {
return "This is person has
" + car;
}
}
public
class Car {
public Car() {}
}
|
public
class CopyConstructorMain {
public static void main(String [] args) {
Person person1 = new Person(new
Car(), "Ben");
Person person2 = new Person(person1);
System.out.println(person1);
System.out.println(person2);
}
}
Output is:
----------
This is
person has Car@4edbb0
This is
person has Car@3f75e0
|
Shallow Copy
|
Deep Copy
|
public
class Color {
private String color;
public Color(String c){
this.color = c;
}
//getters and setters for the fields
should go here........
}
public
class ColoredCircle implements Cloneable {
private int centerX;
private int centerY;
private Color color;
public ColoredCircle(int x,
int y, Color c){
this.centerX = x;
this.centerY =
y;
this.color =
c;
}
public Object clone() {
try {
return (ColoredCircle)super.clone();
}
catch
(CloneNotSupportedException e) {
// This
should never happen
}
}
//getters and setters for the fields
should go here........
}
public
class CloneMain {
public static void main(String [] args) {
Color c =
new Color("RED");
ColoredCircle
c1 = new ColoredCircle(200,200,c);
ColoredCircle c2 = c1.clone();
}
}
|
public
class Color implements Cloneable{
private String color;
public Color(String c){
this.color = c;
}
public Object clone() {
try {
return (Color)super.clone();
}
catch
(CloneNotSupportedException e) {
// This
should never happen
}
}
//getters and setters for the fields
should go here........
}
public
class ColoredCircle implements
Cloneable {
private int centerX;
private int centerY;
private Color color;
public ColoredCircle(int x, int y, Color
c){
this.centerX = x;
this.centerY = y;
this.color = c;
}
public Object clone() {
ColoredCircle
coloredCircle = null;
try {
coloredCircle =
(ColoredCircle)super.clone();
}
catch
(CloneNotSupportedException e) {
// This
should never happen
}
coloredCircle.color
= (Color) color.clone();
return coloredCircle;
}
//getters and setters for the fields
should go here........
}
|