---
title: "Problem med clone()"
type: "forum-thread"
url: "https://www.webforum.nu/amne/java/75670-problem-med-clone"
topic: "Java"
topic_url: "https://www.webforum.nu/amne/java"
author: "BABBA"
published: "2003-05-02T10:29:58.000Z"
updated: "2003-05-02T10:54:31.000Z"
replies: 1
views: 247
page: 1
pages: 1
language: "sv-SE"
site: "webForum — webforum.nu"
rights: "Upphovsrätten till varje inlägg tillhör dess författare."
attribution: "Citera som: webForum, https://www.webforum.nu/amne/java/75670-problem-med-clone"
---

# Problem med clone()

## #1 — BABBA, 2003-05-02T10:29Z

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.

Permalänk: https://www.webforum.nu/p/75670

## #2 — aasah, 2003-05-02T10:54Z

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.*

Permalänk: https://www.webforum.nu/p/1032907

---

Tråden på webben: https://www.webforum.nu/amne/java/75670-problem-med-clone
