Constructors and Blocks in Java
Constructors and Blocks in Java
Like methods, a
constructor also contains collection of statements(i.e. instructions) that are executed at time of Object
creation.
➢ Each time an object is created using new() keyword at least one constructor (it could be default
constructor) is invoked to assign initial values to the data members of the same class.
➢ Constructor(s) of a class must has same name as the class name in which it resides.
➢ Access modifiers can be used in constructor declaration to control its access i.e which other class
can call the constructor.
➢ Constructors are not inherited.
3. Copy Constructor in Java: Like C++, Java also supports copy constructor. But, unlike C++, Java
doesn’t create a default copy constructor if you don’t write your own.
class Complex {
private double re, im;
Complex(Complex c) { // copy constructor (Has to be self declared UNLIKE C++)
System.out.println("Copy constructor called");
re = c.re;
im = c.im;
}
}
Constructor Chaining - Constructor chaining is the process of calling one constructor from another
constructor with respect to current object.
Alternative method (using Init block): Initializer block contains the code that is always executed
whenever an instance is created. It is used to declare/initialize the common part of various
constructors of a class.
➢ We can note that the contents of initializer block are executed whenever any constructor is
invoked (before the constructor’s contents).
➢ The order of initialization constructors and initializer block doesn’t matter, initializer block is always
executed before constructor.
➢ Example:
class Temp {
// block to be excuted first
{
System.out.println("init");
}
Temp() {
System.out.println("default");
}
Temp(int x) {
System.out.println(x);
}
// block to be executed after the first block which has been defined above.
{
System.out.println("second");
}
public static void main(String args[]) {
new Temp();
new Temp(10);
}
}
Output :
init
second
default
init
second
10
➢ For more information/examples refer to: https://www.geeksforgeeks.org/instance-initialization-
block-iib-java/
Static Blocks :
➢ Unlike C++, Java supports a special block, called static block (also called static clause) which can
be used for static initializations of a class.
➢ This code inside static block is executed only once: the first time the class is loaded into
memory.
➢ Example:
// filename: Main.java
class Test {
static int i;
int j;
class Main {
public static void main(String args[]) {
// Although we don't have an object of Test, static block is called because i is being accessed in
following statement.
System.out.println(Test.i);
}
}
Output:
static block called
10