Java Clone - Advanced topic

Опубликовано: 13 Июль 2026
на канале: Sankar Srivatsa
10,013
like

In this video, we cover the problems associated with Cloning. The sample code is given for you to understand the topic and problems associated with cloning.

www.SealPointAcademy.com
------------------------


public class SheepClone {

public static void main(String [] agrs) {
Sheep firstSheep = new Sheep("Rambo", 4);
Sheep secondSheep = firstSheep.clone();
Sheep thirdSheep = (Sheep) firstSheep.clone();


secondSheep.name = firstSheep.name;
thirdSheep.name = firstSheep.name;


System.out.println("First Sheep Name " + firstSheep.name + " and age " + firstSheep.age[0]);
System.out.println("Second Sheep Name " + secondSheep.name + " and age " + secondSheep.age[0]);
System.out.println("Third Sheep Name " + thirdSheep.name + " and age " + thirdSheep.age[0]);


firstSheep = null;

// Though the first sheep is now point to nowhere,
// the second sheep and third sheep are accessible

System.out.println("Second Sheep Name " + secondSheep.name + "and age " + secondSheep.age[0]);
System.out.println("Third Sheep Name " + thirdSheep.name + "and age " + thirdSheep.age[0]);


// You should seen the values printed by above two statements
// Try to access the first sheep ...what do you get
System.out.println("First Sheep Name " + firstSheep.name + "and age " + firstSheep.age[0]);

}
}

class Sheep implements Cloneable
{
public String name;
public int[] age ;

Sheep ( String itsName, int itsAge)

{
name = itsName;
age = new int[1] ;
age[0] = itsAge;
}

public Object clone() {

try {
return super.clone();
}
catch (CloneNotSupportedException e)
{
return this;
}


}

}