filmov
tv
How to write a copy constructor in Java - 037

Показать описание
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
▼
▼
Concepts: Java, classes, java copy constructor, constructors
Social Links: Don't hesitate to contact me if you have any further questions.
Related Videos:
What are static factory methods in Java? - 036
Free Java Course Online
Media credits: All images are owned by DJ Spiess unless listed below:
Clipart
Music
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
▼
▼
Concepts: Java, classes, java copy constructor, constructors
Social Links: Don't hesitate to contact me if you have any further questions.
Related Videos:
What are static factory methods in Java? - 036
Free Java Course Online
Media credits: All images are owned by DJ Spiess unless listed below:
Clipart
Music
Комментарии