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 callfoo()
. It's not about the fact thatB
extendsA
, it's thatA
is in the same package asB
. - Subclasses can invoke it.. on themselves only. Trivially (but this doesn't work if its
final
), you can simply override it, implement it asreturn super.clone();
and now you can call it just fine.
Answered By - rzwitserloot Answer Checked By - Katrina (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.