Skip to main content
gamedev.net
🔒 Locked

[java] Why is clone protected?

Started by Mulligan Oct 30, 2002 at 8:09 PM 3 replies 550+ views
Original Post
Mulligan
Mulligan
I keep getting this error stating that "clone() has protected access in java.lang.Object" Why can''t I use clone? The base class: public abstract class Shape implements Cloneable Rect is defined liek this: public class Rect extends Shape void function( Shape s ) { Rect rectCopy = (Rect)s.clone(); // This generates the error }
zephon
zephon
You''ll need to create a method in Shape something like:

public Shape cloneShape()
{
Shape testShape = new Shape();
testShape = this.clone();
return(testShape);
}

then call s.cloneShape();


Protected methods can''t be accessed by anything other than subclasses...
linkki_
linkki_
I''m just guessing here, but I noticed a possible error in your code:

Rect rectCopy = (Rect)s.clone();

Shouldn''t this be like:

Rect rectCopy = ((Rect)s).clone();

?
cyrax256
cyrax256
because clone() can be prone to abuse.

Imagine you have your class (let''s call it One), and you have reference to other classes (Two, and Three). If you clone One, ¿would you have to clone also Two and Three?, or the clone would have the same references to the original Two and Three?

In order to clone an object, you have two options:

1) A constructor which unique parameter is an object of the same class, and in the constructor you assign the instance variables...

public One(One otherClass) {
this.firstVariable = otherClass.firstVariable;
this.secondVariable = otherClass.secondVariable;
//and so on...
}

2) Make a public cloning method which returns the clone of the object (Warning: you have to tag first the class by implementing the Cloneable interface)

class One implements Cloneable {
//bla bla bla
public One cloneOne() {
return this.clone();
}//more bla bla bla
}
I''m a bit sleepy, and too lazy to check this, if any errors, sorry
Jiim
Jiim
First, correct a few posters.

* A protected method/field is accessible to any subclasses *and* to any classes in the same package.

* (Rect) s.clone() is what was meant and is correct.

Now, a couple of suggestions,

Are you actually defining your own clone() method for Rect?? I''m not clear on this point but this might explain your problem. The clone() method that will actually be called will lie in the java.lang package, whereas your error is in a class in (presumably) the default package.

Or, is Rect in a different package to the line generating there error?

Jiim Jonez
www.javage.net

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.