0% found this document useful (0 votes)
91 views

Constructor in Java

Constructor in Java is used to initialize an object. There are three types of constructors: default, no-args, and parameterized. Constructors can be overloaded and chained. A constructor call must be the first statement in another constructor. Constructors cannot be static, abstract, or final. Copy constructors make deep copies of objects. Singleton classes restrict instantiation to one object using private constructors. Initializer blocks run before constructors during object instantiation.

Uploaded by

qwermnb
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
91 views

Constructor in Java

Constructor in Java is used to initialize an object. There are three types of constructors: default, no-args, and parameterized. Constructors can be overloaded and chained. A constructor call must be the first statement in another constructor. Constructors cannot be static, abstract, or final. Copy constructors make deep copies of objects. Singleton classes restrict instantiation to one object using private constructors. Initializer blocks run before constructors during object instantiation.

Uploaded by

qwermnb
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Constructor in Java

Constructor in java is used to create the instance of the class.  A constructor cannot be enclosed inside a
try/catch block.

Whenever we use new keyword to create an instance of a class, the constructor is invoked, and the
object of the class is returned. There are no “return value” statements in constructor, but constructor
returns current class instance. We can write ‘return’ inside a constructor.
Void return is possible in constructor. If we add return type, it becomes method

There are three types of constructor in java.

1. Default Constructor - initialize the object, without argument & called when no constructor is
defined. default constructor in Java initializes member data variable to default values
2. No-Args constructor - It’s like overriding the default constructor & do some tasks
3. Parameterized constructor

Constructors can be overloaded. Sometimes there is a need of initializing an object in different ways.
Constructors cannot be static as they are the property of object & not class. Constructors cannot be abstract as
they cannot exist without body and are executed after new keyword. Constructors cannot be final as they are
never inherited and therefore are not subject to hiding or overriding.

Constructors can be chained with each other. Constructor calling other constructors. Another constructor call
should be the first statement in the code block. Also, there should not be recursive calls that will create
an infinite loop. 

Super () -> if we have to call superclass constructor.  super constructor call should be the first statement
in the child class constructor. Also when instantiating child class constructor, java first initializes the
super class and then child class. So if the super class constructor is not explicitly called then default or
no-args constructor of parent class is called by java runtime. You can call any type of constructor from
child class’s constructor. There is no way in java to call sub class constructor from a super class constructor.

If we provide parametrized constructor, it overrides default constructor. You need to give parameters in new
Object (). You can’t leave it blank.
Copy Constructor ->

Notice that when copy constructor is used, both the original object and its copy are unrelated to each
other and any modifications in one of them will not reflect into other.

Java copy constructor takes the object of the same class as an argument and creates a copy of it.
Sometimes we need a copy of another object to do some processing. We can do this by following ways:
implement cloning AND providing a utility method for deep copy of the object AND Having a copy
constructor

constructor chaining reason -> modularized & readable code

Private Constructors -> constructors is made private in case we want to implement singleton design
pattern. Since java automatically provides default constructor, we have to explicitly create a constructor
and keep it private. Client classes are provided with a utility static method to get the instance of the
class. A private constructor cannot be used to initialize an object outside the class that it is defined within
because it is no longer visible to the external class.

 Constructor(s) must have the same name as the class within which it defined while it is not
necessary for the method in java.
 Constructor(s) do not return any type while method(s) have the return type or void if does not
return any value.
 Constructor is called only once at the time of Object creation while method(s) can be called any
numbers of time.

Because Java is a garbage collected language you cannot predict when (or even if) an object will be destroyed.
Hence there is no direct equivalent of a destructor.

Init Blocks

When we want certain common resources to be executed with every constructor we can put the code in
the init block. Init block is always executed before any constructor, whenever a constructor is used for
creating a new object. NOTE: If there are more than one blocks, they are executed in the order in which
they are defined within the same class. Initializer block contains the code that is always executed
whenever an instance is created.

non-static final variables can be assigned a value either in constructor or with the declaration or with init
block. But static final variables cannot be assigned value in constructor; they must be assigned a value
with their declaration or inside static block (as they are properties of class).

Singleton Class
The singleton pattern is a design pattern that restricts the instantiation of a class to one object.
Instance should be globally accessible .
java.lang.Runtime and java.awt.Desktop are 2 singleton classes provided by JVM.
Example : Cache: We can use the cache as a singleton object as it can have a global point of reference
and for all future calls to the cache object the client application will use the in-memory object.

The main problem with above


method is that it is not thread
safe. The first time
getInstance() is called it
creates a new singleton object
and after that it just returns
the same object. Note that
Singleton obj is not created
until we need it and call
Method 1 -> getInstance() method. This is

Method 2 ->
Using synchronized makes sure that
only one thread at a time can execute
getInstance().
The main disadvantage of this is
method is that using synchronized
every time while creating the
singleton object is expensive and
may decrease the performance of
your program. However if
performance of getInstance() is not
critical for your application this
method provides a clean and simple
solution.

Method 3 ->
Here we have created instance of
singleton in static initializer. JVM
executes static initializer when the
class is loaded and hence this is
guaranteed to be thread safe. Use
this method only when your
singleton class is light and is used
throughout the execution of your
program.
Double lock check
a software design
pattern used to reduce the
overhead of acquiring
a lock by testing the locking
criterion before acquiring
the lock. Locking occurs
only if the locking criterion
check indicates that locking
is required.

Method 4 ->
JVM inherits main method.

Collections in Java
Collection is a group of objects.
1. quals(Object otherObject) – As method name suggests, is used to simply verify the equality of two
objects. It’s default implementation simply check the object references of two objects to verify their
equality. By default, two objects are equal if and only if they are stored in the same memory address.
2. hashcode() – Returns a unique integer value for the object in runtime. By default, integer value is mostly
derived from memory address of the object in heap (but it’s not mandatory always).
This hash code is used for determining the bucket location, when this object needs to be stored in
some HashTable like data structure.

You might also like