Constructor: it
is a special method given in OOP language for creating and initializing object.
In java, constructor role is only initializing object, and new keyword role is creating object. In C++, constructor alone
creates and initializes object. If we do not define constructor compiler will
define constructor.
Rules in defining constructor:
Constructor name should be same as class name. Every
class object is created by using the same new keyword, so it must have
information about the class to which it must create object. For this reason
constructor name should be same as class name.
- it should not contain return type. If place
return type in constructor will leads to compile Error because compiler and JVM
consider it as method.
- IT should not contain modifiers
- In its logic return statement with value is not
allowed.
- It can have all four accessibility modifiers.
- It can have parameters.
- It can have throws clause – it means we can
throw exception from constructor.
- It can have logic, as part of logic it can have
all java legal statement except return statement with value
- We can place return; in constructor.
Class Example {
Example {
Statements except return;
} }
Calling Constructor: it must
be called along with “new” keyword; else it leads to compile time error.
Can we define a method with same class name?
Yes, it is allowed to define a
method with same class name. No compile time error and no runtime error are
raised, but it not recommended as per coding standards.
How compiler and JVM can differentiate constructor and method definitions;
and invocations if both have same class name?
By using return type, if there is
return type it is considered as method else it considered as constructor.
By using new keyword, if new
keyword is used in calling then constructor is executed else method executed.
We can define empty class, but
after compilation it will have constructor definition that is placed by
compiler. So really it is not an empty class.
How can we know that compiler places constructor in class file?
We should use “javap” tool. It is a java binary file available in “jdk\bin”
folder. It is used to decompile class file to check that class members. Javap tool
only displays class member’s prototype. It does not show body and logic. Ex: javap classname
Java supports 3 types of
constructors:
Default constructor: the compiler given constructor is called
default constructor. It does not parameters and logic except super() method call.
No argument/non-parameterized constructor: the developer given
constructor without parameter is called no-arg /non-parameterized constructor.
Parameterized constructor: the developer given constructor with
parameter is called parameterized constructor. In this we can have logic.
Super() method call must also be placed as a first statement in
developer given constructors. If developer does not place it, compiler will
place this statement.
why compiler given constructor is called default constructor?
Because it obtain all its default
properties from its class they are:
Its accessibility modifier is same
as its class accessibility modifier
Its name is same as its class
name.
It does not have parameters and
logic.
Why compiler defines default constructor without logic and parameters?
Because compiler does not know
logic required for your class. The objects initialization logic is different
from one class to another class.
But it places super() method call
in all constructors because it is generic logic required for every class for
calling super class constructor in order to initialize super class non-static
variables when subclass object is created.
Since there is no logic in default
constructor, compiler defines constructor without parameters.
When developer must provide constructor explicitly?
If we want to execute some logic
at the time of object creation that logic may be object initialization logic or
some other useful logic.
We must create object of a class by using
new keyword and available constructor.
To initialize object dynamically with the
user given values then we should defined parameterized constructor.
In a class we can define multiple
constructors, but every constructor must have different parameters type or
parameters order. So in a class we can define one no-argument constructor + ‘n’
number of parameterized constructors.
Defining multiple constructors with
different parameter types/order/list is called
constructor overloading.
Ex: Example
() {}
Example (int i) {}
Example (String str) {}
NON-Static
BLOCK: (NSB) a class level block
which doesn’t have prototype is called non-static block.
We should define non-static block to
execute some logic only at the time of object creation irrespective of the constructor
used in object creation. NSB is executed automatically by JVM for every object
creation in java stacks area by creating separate stack frame. NSB always
executed before constructor.
Class example {
{
Sopln (“NSB Block”); }
Example () { Sopln (“Constructor”); }
}
We can define multiple non static blocks. When
an object is created first all non static variables and non-static blocks are
executed in the order they are defined from top to bottom, then the invoked
constructor logic is executed.
Compile
Time Error: illegal forward reference: a class level variable should be
accessed directly before its creation statement either from other variables,
from blocks. It leads to that error. But it is possible to access those
variables from methods and constructors, because they are always executed after
variable execution. Call static variable with “class name”, and non static
variable with “this”.
Recursive
method and constructor call: calling a method or constructor from its own
block is called recursive method or constructor call. In both cases program is
terminated with java.lang.StackOverFlowError.
Because due to this call stack frames are
created continuosly without destroying previous stack frames. Due to this
reason at some point of time there will not be memory in thread to create new
stack frame.
Class Example{
Static void m1(){
Sopln(“m1”);
M1();
} }
We can create object at class level using
static and non-static referenced variables, but the object creation using
non-static referenced variable also leads to java.lang.StackOverflowError. it
is possible to create object at class level using static referenced variable. Object
of same class should not be created using non static referenced variable or in
non-static block or in same constructor it leads to exception above.
Class A {
Static A a=new A();
A a=new A(); /// it leads to execption.
A(){
}
}