This is the second half of the two-part series on the syntactic comparison of Java and C/C++. Before we begin, I’d like to encourage you to read its first part if by any chance you’ve missed it. It is called “Syntactic Comparison of Java and C/C++” and it’s published right here. You shouldn’t miss it because grasping the basics is crucial.
In Java to set the relationship between a parent and child class you need to use the extends keyword. Likewise, the keyword this works the same as it does in C/C++; it stands for referring to the method itself. Additionally, Java has super that is used when you want to refer to a method that’s within a parent class.
Now let’s talk about constructors and destructors. A constructor is a method that basically defines the way an/more object(s) should be created. These do not return any kinds of values. Each class in Java can contain one or more constructors. We all know that in C/C++ destructors were used to free up the memory that was allocated to a particular object. However, this isn’t the way Java works. Destructors aren’t required.
In Java there’s a new addition called garbage collection. What this collector does is quite simple to understand. On a very frequent basis it verifies all of the references in all objects; due to this, it classifies each of them as either live or dead. References that do not exist (cannot be reached) are rapidly freed up from the memory.
As a result, destructors aren’t necessary anymore. Garbage collector (GC) does it more efficiently than any coder could explicitly do it in C/C++. It won’t free up live objects by mistake, nor will it forget to perform the task of freeing memory and thus leave dead objects further clogging up the memory. Once you get the hang of Java you’ll realize that GC is great!
Nevertheless, nobody prevents you from explicitly freeing up the objects. There’s a method called finalize() that indeed finalizes an object. Each class can contain the finalize method because it’s defined within the Object superclass, therefore every class inherits it. Calling finalize is akin to freeing up the object before it gets collected by the GC (read as: freed up automatically).