Constructor in Java is a block of code which is mainly used
for creating and initializing the objects. Syntax of constructors is like
syntax of method so if you see, normally constructors do not differ much from
methods, but they must have simple class name as name and they must not have
any return type.
Syntax
to declare the constructors:
[modifier(s)]
([parameter(s
)]) [throws throwable]
)]) [throws throwable]
{
//Body of constructor.
}
The modifiers like private, public, protected can be use with
constructors to define their scope specifically. Constructor must have class
name as its name.
If you specify return type to the constructor then it will be
treated as method.
Ex:
class Student{
public Student(){ //Constructor
for student class.
//Statements.
}
Public void Student() //Will
be method as it has return type.
{
//Statements
}
Compiler will place a default constructor if you are not
providing any constructor explicitly. A default constructor placed by compiler
automatically, will be a constructor with no arguments. If you specify a
constructor then compiler will not provide any default constructor.
To make your class and object usable with reflections and
other frameworks the constructor must be constructor with no arguments or
default constructor provided by the compiler. We can also define no argument
constructor for creating and initiating the objects.
Compiler will place super() call to immediate parent call
constructor in any constructor if:
·
No super() call is provided by the programmer.
·
No this() call is provided by the programmer.
The aim of placing super() call is to propagate constructor
class to parent class and lastly to java.lang.Object class constructor; because
if your constructor is not following this hierarchy then it will be impossible
for compiler to allocate memory for your constructor as memory will be
allocated for object of all classes which are in inheritance hierarchy of from
object class to class provided in instance creation expression.
Constructors can be overloaded i.e. more than one
constructors can be provided in same class but with different type
signature/parameters. To call such overloaded constructors you can use ‘this’
keyword.
But if you are using ‘this’ keyword then it must be the
first statement in the constructor.
You can use super() call to call the parent class
constructor but when you use it, it must be first statement in the constructor.
So from above two statements we can say that we can not have
combination of ‘this’ and ‘super’
keywords in a constructor at same time.
The process of calling constructor from child class to
parent class and executing the constructor in reverse order is called
constructor chaining.
Process of calling one constructor from other is called as
constructor chaining and you must place call to another constructor as first
line of any other constructor.
There is no destructor in Java, like C++.
0 comments:
Post a Comment