BABBAMedlem sedan feb. 2000280 inlägg Hej
Jag har två olika klasser, den ena heter Ticket och den andra TimeHandler. I Ticket vill jag klona ett object av TImeHandler men jag får error = "clone() has protected access in java.lang.Object"
min kod i Ticket ser ut så här:
public TimeHandler setEndTime(TimeHandler o){
TimeHandler r = o.clone();
return r;
}
Jag vill alltså klona en TimeHandler och returnera den nya. Hur fasen gör jag det??
Jag implementerar Cloneable i TimeHandler.
aasahMedlem sedan mars 20034 471 inlägg Re: Problem med clone()
BABBA skrev:
Jag har två olika klasser, den ena heter Ticket och den andra TimeHandler. I Ticket vill jag klona ett object av TImeHandler men jag får error = "clone() has protected access in java.lang.Object"
Problemet är att i klassen Object har clone() definierats enl:
protected Object clone()
Creates and returns a copy of this object
Detta innebär att clone() kan anropas inuti en klass, men inte utanför. Dessutom bör du notera följande från Javas api:
The method clone for class Object performs a specific cloning operation. First, if the class of this object does not implement the interface Cloneable, then a CloneNotSupportedException is thrown. Note that all arrays are considered to implement the interface Cloneable. Otherwise, this method creates a new instance of the class of this object and initializes all its fields with exactly the contents of the corresponding fields of this object, as if by assignment; the contents of the fields are not themselves cloned. Thus, this method performs a "shallow copy" of this object, not a "deep copy" operation.