1

clone() method in the Object class is protected, so why I have an error?

public class Test
{
    public static void main(String[] args)
    {
        Test2 c1 = new Test2();
        Test2 c2 = (Test2) c1.clone(); // error: clone() has protected access in java.lang.Object
    }
}

class Test2 implements Cloneable
{

}
Denys_newbie
  • 1,140
  • 5
  • 15
  • 2
    @jwpol Getting links right is infuriating sometimes, isn't it?! – Dave Newton Jul 30 '20 at 17:21
  • 1
    Note that `clone` specifically is problematic, and should usually be avoided [See this answer for some details](https://stackoverflow.com/a/1106159/812837). – Clockwork-Muse Jul 30 '20 at 17:26
  • @Dave Newton Definitely, anyway from this thread you can read that you have to override it and make that method protected to use it. https://stackoverflow.com/questions/1138769/why-is-the-clone-method-protected-in-java-lang-object#:~:text=clone%20is%20protected%20because%20it,the%20class%20that%20needs%20it. – jwpol Jul 30 '20 at 17:27

0 Answers0