Saturday, December 10, 2022

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

Issue

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?

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.


Answered By - rzwitserloot
Answer Checked By - Katrina (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.