PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, December 10, 2022

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

 December 10, 2022     java, syntax     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing