Expand the Object object explicitly and call the clone method of throwing errors

I tried the following code to clone an object. when compiling, it shows that the clone is protected and inaccessible, but I had the Object class extended, so the clone method will be public for my class. explain the reason to me.

class storeDate extends Object {

  public static void main(String[] args)
  {

    storeDate d = new storeDate();
    Object o = (storeDate)d;
    o.clone():
  }

}

during compilation i get this error

clone () has secure access in java.lang.Object kkk.clone ();

+3
source share
3 answers

The key here is the package to which the classes belong.

This is explained in JLS clause 6.6.2 :

6.6.2
, , .


:

:

FILE pkg1/A.java ( Object )

package pkg1;
public class A {
    protected void method() {};
}

FILE pkg2/B.java ( storeDate )

package pkg2;
import pkg1.A;
public class B extends A {
    public static void main(String args[]) {
        new A().method();
    }
}

javac :

pkg2/B.java:5: method() has protected access in pkg1.A
        new A().method();
               ^

( , : clone() java.lang.Object kkk.clone();)


B pkg1 .

, :

FILE pkg1/A.java ( )

package pkg1;
public class A {
    protected void method() {};
}

FILE pkg1/B.java ( pkg2 pkg1)

package pkg1;                 // Changed from pkg2
//import pkg1.A;              // Not necessary anymore.
public class B extends A {
    public static void main(String args[]) {
        new A().method();
    }
}

, , - new Object().clone()? , java.lang (, , SecurityException: Prohibited package name: java.lang).

+1

clone Object. clone() super.clone(), Object.clone. .

Cloneable ( ).


( ) ( Cloneable) , , . Object#clone , Object (= ) clone() java.lang package can access clone() ` .

. nice matrix.

+1

clone? , Java clone .

-

, , , , clone . [...] , Cloneable , .

" Java 2- ", 11: clone. factory.

, , , clone. :

? . , Cloneable, , clone. .

, . , .


, ?

:

factory.

In this case, it can be implemented simply using the constructor StoreDate, which takes another one StoreDate, or provides a utility method static StoreDate newInstanceFrom(StoreDate other).

Related Questions

+1
source

Source: https://habr.com/ru/post/1749350/


All Articles