Reputation: 774
I am curious how Java supports copy constructor and how is it different from C++? I would like to understand the Java equivalent of the logic to execute rule of three (copy constructor, destructor, assignment operator) from the compiler side of the story.
Upvotes: 5
Views: 1655
Reputation: 533530
Java only has references to objects. You can't declare inline (on stack or in object) objects.
copy constructor
Java doesn't have one. You can write one but this is rarely done.
, destructor
Java doesn't have one. It has finalize()
but this is highly discouraged.
assignment operator
Java doesn't have one for objects, only references to objects.
Upvotes: 5
Reputation: 718906
Java has no specific linguistic support for copy constructors. Rather you just code the state copying by hand in the constructor; e.g.
public class Person {
private String firstName;
private String lastName;
public Person(Person other) {
this.firstName = other.firstName;
this.lastName = other.lastName;
}
...
}
I would like to understand the Java equivalent of the logic to execute rule of three (copy constructor, destructor, assignment operator) from the compiler side of the story.
The copy constructor is as above. Is really just a (simple) design pattern.
Java doesn't provide an equivalent to C++ assignment operator loading. Java supports assignment of primitive types and reference types, but not assignment of objects in the same way that C++ does. It is unusual for special actions are required when assigning a value in Java. And in the cases where you need to do this, it is customary to put the logic into a setter method.
Java supports finalize
methods, that are similar in some respects to C++ destructors. The primary differences are that finalize
methods are operations on objects not reference variables, and they are typically called a long time after the object's last reference has gone out of scope.
However, you rarely need to use finalize
methods:
Java is a fully garbage collected language, and the best strategy for memory management is to just let the GC take care of it.
Other resources are best managed using "try / finally" or "try with resources".
AFAIK, the only sound use-case for finalize
methods is for cleaning up resources that have been lost accidentally; e.g. because someone forgot to "close" them using the recommended mechanisms.
Upvotes: 8