1

This class must have a clone() method, so that copies of it can be made. I tried putting one in, but it is missing a return? What exactly do you return in a clone method?

This is the class I am trying to give a clone() method:

package planets;

public class Planet extends shape3D.Sphere {
    String myPrimaryGas;    
    public void setPrimaryGas(String primaryGas){
        myPrimaryGas = primaryGas;
    }
    public String getPrimaryGas(){
        return myPrimaryGas;
    }
}
4
  • Where is your attempt at a clone method?
    – CPerkins
    Sep 18, 2013 at 19:28
  • Have you tried to google that? There's event a Wikipedia article about this topic :) en.wikipedia.org/wiki/Clone_(Java_method)
    – ibtarek
    Sep 18, 2013 at 19:30
  • Shallow or deep clone ? does shape3D.Sphere support cloning (implements Cloneable ?
    – Nir Alfasi
    Sep 18, 2013 at 19:31
  • Not sure if shallow or deep. It just says "All of your methods need a clone() method to create copies" Sep 18, 2013 at 19:36

1 Answer 1

1

What your clone does (in java) is essentially create a second object, of type Planet (in this case), and copies all the values so that you have two identical objects, the new one, and 'this'.

So your clone would be something like

public Planet clone (){
    Planet p = new Planet (myPrimaryGas);
    return p;
}

or in your case, it seems like you have no constructor defined, so this :

public Planet clone (){
    Planet p = new Planet ();
    p.setPrimaryGas(myPrimaryGas);
    return p;
}

Keep in mind, you want a "deep copy" ... meaning you need to call clone for all objects inside of this one. The only reason I can use "myPrimaryGas" and not "myPrimaryGas.clone()" is because Strings are (almost) a primitive type

6
  • Often in order to make cloning works, involves a private constructor to really directly assign things.
    – Cruncher
    Sep 18, 2013 at 19:32
  • 1
    Also, the real reason you don't need to clone Strings is because Strings in java are immutable.
    – Cruncher
    Sep 18, 2013 at 19:35
  • Yes, there won't be any issues of modifying the object from two locations. For most intents Strings in java can be handled as if they were integers
    – Chris
    Sep 18, 2013 at 19:38
  • "12" + "3" == "123": false. 12 + 3 == 15: true
    – Cruncher
    Sep 18, 2013 at 19:41
  • @Cruncher I agree with your initial comment but it happens that "12" + "3" == "123" is true...
    – assylias
    Sep 18, 2013 at 21:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.