Java

Java Basic (5) - Object, clone(), copy

Kate Choi 2021. 5. 19. 01:12

 


Object

  • every type except double, float, long, int, short, byte, char, or boolean is an Object
  • includes String, all arrays, your own classes, any pre=supplied classes like Scanner or ArrayList
  • these types store a reference to an object, never the object itself

 


Clone

  • Needed to make a completely new object, identical to an existing one
  • Gives two independent objects (not shallow copy) -> a change to one will not affect the other

 

smithClone was created using clone()
clone() method. The return type is the same as type as the current object
output
A change to the original object
output : the clone hasn't changed


Cloning Arrays

 

output

 

or use shortcut

 


Cloning Array of Object

  • Use .clone() (deepcopy)

 

It just copies the reference
output : the copied array affected by the change of the original array (shallow copy). 
we get two different arrays of Person objects, but the references to the Persons were only copied
output
Deep copy using .clone() to make two fully independent copies
output