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();
}
}
CodePudding user response:
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.
CodePudding user response:
protected members can be accessed anywhere in the same package and outside package only in its child class and using the child class reference variable only, not on the reference variable of the parent class. We cant access protected members using the parent class reference.