Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloning an Integer

Tags:

java

cloneable

I am trying to clone a object of class Integer, which does implement the cloneable inteface.

Integer a = new Integer(4);  
Integer b = a.clone();

I know there are work arounds for this, but I must implement it like this. why I am getting this error = clone() has protected access in java.lang.Object

Why would it say this? Isn't the clone method a public abstract method of clonable interface, what does it have to do with object. Thanks in advance :-)

like image 264
rubixibuc Avatar asked Apr 28 '11 06:04

rubixibuc


2 Answers

java.lang.Integers are immutable. There is no reason to clone one. If you're trying to waste memory, try Integer.valueOf(myInteger.intValue()).

like image 144
rlibby Avatar answered Oct 06 '22 06:10

rlibby


Sure, all methods in Object are inherited. The clone method however is protected, thus only accessible from within subclasses.

The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

The reason why you can call clone() in most other circumstances is that the subclass "opens it up" by overriding it with the public access modifier.

like image 29
aioobe Avatar answered Oct 06 '22 06:10

aioobe