首页 > 解决方案 > Why can't we use clone method by using approch 1(given below) instead of approch 2 and what's need of marker interface? Why jvm handle clone method?

问题描述

approach 2

/*Using clone method by using marker interface and clone method control by jvm (recommended way)*/
class Employee implements Clonable
{
String name,id;
Employee(String name,String id)
{
this.name=name;
this.id=id;
}
public Employee clone()
throws CloneNotSupportedException
{
return (Employee)super.clone();
}
}
public class ObjectClone
{
public static void main(String[] args)
{
Employee obj1 = new Emloyee("test","6");
Employee obj2=obj1.clone();
}
}

approch 1

/*without using marker interface control clone method by me (not recommended)*/

class Employee extends Object
{
String name,id;
Employee(String name,String id)
{
this.name=name;
this.id=id;
}
public Employee clone()
throws CloneNotSupportedException
{
return (Employee)super.clone();
}
}
public class ObjectClone
{
public static void main(String[] args)
{
Employee obj1 = new Emloyee("test","6");
Employee obj2=obj1.clone();
}
}

标签: javacloneablemarker-interfaces

解决方案


推荐阅读