Bin_Z
Bin_Z

Reputation: 919

call clone() in my own class

I know that there is a clone() method in Object class which is declared as protected, so that means I can call clone() in my own class since every class inherits from Object class, for example :

public class CloneTest
{
    public static void main(String args[])
    {
        Employee employee1 = new Employee(...);
        Employee employee2 = employee1.clone(); // but here has 2 errors
    }
}

class Employee
{
    ...
}

first error is something about "access protected in Object"
second error is "incompatible type"
Why these errors happen ?

Upvotes: 0

Views: 1100

Answers (4)

amicngh
amicngh

Reputation: 7899

The first error is because .clone is protected in the Object class. It's not public.`

The only way to get access to an object's .clone() method is to know it has a compile-time type that has a public .clone() method.

Override clone method in Employee Class

 class Employee implements Cloneable
{
   @Override
   protected Employee clone() throws CloneNotSupportedException {
    // TODO Auto-generated method stub
    return (Employee)super.clone();
}
}
}

Upvotes: 0

Denys Séguret
Denys Séguret

Reputation: 382514

The clone method returns an Object if not overridden. So you must cast the result :

Employee employee2 = (Employee) employee1.clone();

The first error is related to the content of the Employee class, that we don't see. Does it override the clone method ? It should, that's the condition to have it accessible from other classes that the called class.

Upvotes: 3

dcernahoschi
dcernahoschi

Reputation: 15250

Your Employee class should look something like this for clone() to work:

public class Employee implements Cloneable {
    ...

    public Employee clone() {
        try {
            return (Employee) super.clone();
        }
        catch(CloneNotSupportedException e) {
            throe new IllegalStateException("I forgot to implement cloneable");
        }
    }

    ...
}

The first error is because clone has protected access in the Object class and the second one is because it returns Object by default.

Upvotes: 1

SnailCoil
SnailCoil

Reputation: 808

You need to do a few things in order to use the clone method. See: http://www.javapractices.com/topic/TopicAction.do?Id=71

Upvotes: 0

Related Questions