How to write a copy constructor in Java - 037

Опубликовано: 22 Октябрь 2015
на канале: Deege
35,726
736

What if we want to create an instance that's just like the one over there? We just want a copy. This video looks at the copy constructor in Java, and how to create new identical instances.

A copy constructor is this. It's a method that takes an instance of a class, and returns a new instance copied exactly like the first class. You can use a static factory method, but best practice is use a constructor that takes a single instance of the class as a parameter. We'll create our copy constructor to use a constructor.

What goes in our copy constructor? Well the next thought is to create a new enemy object, and copy the attributes over. That looks like this. Unfortunately this doesn't work either. We wanted two enemies, but we really got two enemies sharing a weapon and toolbelt. If we change a value on one weapon, say to overheating, both enemies will experience the change. That's because we did something called a shallow copy.

#java #programming #tutorial


Like the video? Don't forget to subscribe! ➜ http://www.deegeu.com/subscribe


Keep up to date with the newsletter! ➜ http://www.deegeu.com/newsletter/

Transcript and code: : http://www.deegeu.com/java-copy-const...

Concepts: Java, classes, java copy constructor, constructors

Social Links: Don't hesitate to contact me if you have any further questions.
WEBSITE : [email protected]
TWITTER :   / deege  
FACEBOOK:   / deegeu.programming.tutorials  
GOOGLE+ : http://google.com/+Deegeu-programming...

About Me: http://www.deegeu.com/about-programmi...

Related Videos:

What are static factory methods in Java? - 036
   • What are static factory methods in Ja...  

Free Java Course Online
   • What important Java Terms do I need t...  

Media credits: All images are owned by DJ Spiess unless listed below:

Clipart
https://openclipart.org/

Music
Just Nasty by Kevin MacLeod is licensed under a Creative Commons Attribution license (https://creativecommons.org/licenses/...)
Source: http://incompetech.com/music/royalty-...
Artist: http://incompetech.com/