Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why I'm facing with 'clone() has protected access in java.lang.Object' compiler error?

Object’s clone method is protected, therefore it can be accessed in sub classes (class A), so why am I getting ‘clone() has protected access in java.lang.Object’ compiler error? I thought, that all Java classes are sub classes of Object. Thanks in advance.

The code below raises the compiler error:

public class A {
    public static void main(String[] args) {
        Object o = new Object();
        o.clone();//error
    }
}

But this one compiles perfectly, don’t they have the same semantics tho?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public class A {
    protected void foo() {

    }
}
public class B extends A {
    public static void main(String[] args) {
        A a = new A();
        a.foo();
    }
}

>Solution :

No, they don’t.

protected means 2 things:

  • It’s like package, _and that explains why your second snippet can call foo(). It’s not about the fact that B extends A, it’s that A is in the same package as B.
  • Subclasses can invoke it.. on themselves only. Trivially (but this doesn’t work if its final), you can simply override it, implement it as return super.clone(); and now you can call it just fine.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading