Constructor , Variable hiding and Garbage collection in Java
Constructor
It is tedious to initialize all
of the variables in a class each time an instance is created, even when we add
convenience functions to initialize them. It would be much simpler and more
concise to have all of the set up done at the time. The object
is first created a constructor solves this problem by initializing an object
immediately upon creation.
It has the same name as the class in which it resides and is syntactically similar to a method once defined to a constructor is automatically called when the object is created before the new operator completes.
We do not write any return type of the constructor because the implicit return type of the constructor is the class type itself in which it resides. Its constructor’s job to initialize the internal set of an object so that the code creating an instance will have a fully initialized a useable object immediately.
It has the same name as the class in which it resides and is syntactically similar to a method once defined to a constructor is automatically called when the object is created before the new operator completes.
We do not write any return type of the constructor because the implicit return type of the constructor is the class type itself in which it resides. Its constructor’s job to initialize the internal set of an object so that the code creating an instance will have a fully initialized a useable object immediately.
As we can see class A has a
constructor which initializes its member variable a with the value of parameter
passed to it.
Variable hiding
It is not allowed in java to
declare two local variables with the same name inside same scopes. Although it
is allowed to have local variables including formal parameters to methods which
overlap with the name of the class instance variable. Although whenever a local
variable has the same name as the instance variable, the local variable hides
the instance variable. This phenomenon is called instance variable hiding.
Whenever this happens, we can access the instance variable by using ‘this’
keyword which is used to refer the current object.
class Acc
{
int
id;
Acc
(int id)
{
this.id = id;
}
}
In this code instance
variable id is hidden by the formal parameter id of constructor Acc. Thus, we
have used this keyword to access the instance variable id.
Garbage collection
Since in java objects are dynamically allocated by a new operator It is very important to destroy the objects so that the memory occupied by the objects can be released for later reallocation. Java handles deallocation of memory by itself. The technique by which java accomplishes this is called garbage collection.
No comments:
Post a Comment