KEMBAR78
Java Constructors | PDF | Constructor (Object Oriented Programming) | Programming
0% found this document useful (0 votes)
12 views14 pages

Java Constructors

Java constructors are special blocks of code used for object creation and initialization, having the same name as the class and no return type. There are three types of constructors: default, parameterized, and copy constructors, each serving different initialization needs. Constructor overloading allows multiple constructors in a class with different parameter lists, enhancing flexibility in object instantiation.

Uploaded by

Pooja N
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views14 pages

Java Constructors

Java constructors are special blocks of code used for object creation and initialization, having the same name as the class and no return type. There are three types of constructors: default, parameterized, and copy constructors, each serving different initialization needs. Constructor overloading allows multiple constructors in a class with different parameter lists, enhancing flexibility in object instantiation.

Uploaded by

Pooja N
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Java Constructors

In Java, constructors play an important role in object creation. A constructor is a special block of code that is called
when an object is created. Its main job is to initialize the object, to set up its internal state, or to assign default values
to its attributes. This process happens automatically when we use the "new" keyword to create an object.
Characteristics of Constructors:
• Same Name as the Class: A constructor has the same name as the class in which it is defined.
• No Return Type: Constructors do not have any return type, not even void. The main purpose of a
constructor is to initialize the object, not to return a value.
• Automatically Called on Object Creation: When an object of a class is created, the constructor is called
automatically to initialize the object’s attributes.
• Used to Set Initial Values for Object Attributes: Constructors are primarily used to set the initial state
or values of an object’s attributes when it is created.
Now, let us look at a simple example to understand how a constructor works in Java.
Example: This program demonstrates how a constructor is automatically called when an object is created in Java.
// Java Program to demonstrate
// Constructor usage
import java.io.*;

// Driver Class
class Geeks {

// Constructor
Geeks()
{
super();
System.out.println("Constructor Called");
}

// main function
public static void main(String[] args)
{
Geeks geek = new Geeks();
}
}

Output
Constructor Called

Note: It is not necessary to write a constructor for a class. It is because the Java compiler creates a default
constructor (constructor with no arguments) if your class doesn't have any.
Constructor vs Method in Java
The below table demonstrates the key difference between Java Constructor and Java Methods.

Features Constructor Method

Constructors must have the


Methods can have any valid
same name as the class
name
Name name

Methods have the return type


Constructors do not return
or void if does not return any
any type
Return Type value.

Constructors are called


automatically with new Methods are called explicitly
Invocation keyword
Features Constructor Method

Constructors are used to Methods are used to perform


Purpose initialize objects operations

Now let us come up with the syntax for the constructor being invoked at the time of object or instance
creation.
class Geek
{
......
// A Constructor
Geek() {
}
.......
}
// We can create an object of the above class
// using the below statement. This statement
// calls above constructor.
Geek obj = new Geek();
The first line of a constructor is a call to super() or this(), (a call to a constructor of a super-class or an overloaded
constructor), if you don't type in the call to super in your constructor the compiler will provide you with a non-
argument call to super at the first line of your code, the super constructor must be called to create an object:

Note: If you think your class is not a subclass it actually is, every class in Java is the subclass of a
class object even if you don't say extends object in your class definition.
Why Do We Need Constructors in Java
Constructors play a very important role, it ensures that an object is properly initialized before use.

What happens when we don't use constructors:


Without constructors:
• Objects might have undefined or default values.
• Extra initialization methods would be required.
• Risk of improper object state
Think of a Box. If we talk about a box class then it will have some class variables (say length, breadth, and height).
But when it comes to creating its object (i.e Box will now exist in the computer's memory), then can a box be there
with no value defined for its dimensions? The answer is No.
So, constructors are used to assign values to the class variables at the time of object creation, either explicitly
done by the programmer or by Java itself (default constructor).
When Java Constructor is Called?
Each time an object is created using a new() keyword, at least one constructor (it could be the default constructor)
is invoked to assign initial values to the data members of the same class. Rules for writing constructors are as
follows:
• The constructor of a class must have the same name as the class name in which it resides.
• A constructor in Java can not be abstract, final, static, or Synchronized.
• Access modifiers can be used in constructor declaration to control its access i.e which other class can
call the constructor.
So, we have learned constructors are used to initialize the object's state. Like methods , a constructor also
contains a collection of statements (i.e. instructions) that are executed at the time of object creation.
Types of Constructors in Java
Now is the correct time to discuss the types of the constructor, so primarily there are three types of constructors in
Java are mentioned below:
• Default Constructor
• Parameterized Constructor
• Copy Constructor
1. Default Constructor in Java
A constructor that has no parameters is known as default constructor. A default constructor is invisible. And if
we write a constructor with no arguments, the compiler does not create a default constructor. Once you define a
constructor (with or without parameters), the compiler no longer provides the default constructor. Defining a
parameterized constructor does not automatically create a no-argument constructor, we must explicitly define if
needed. The default constructor can be implicit or explicit.
• Implicit Default Constructor: If no constructor is defined in a class, the Java compiler automatically
provides a default constructor. This constructor doesn’t take any parameters and initializes the object
with default values, such as 0 for numbers, null for objects.
• Explicit Default Constructor: If we define a constructor that takes no parameters, it's called an
explicit default constructor. This constructor replaces the one the compiler would normally create
automatically. Once you define any constructor (with or without parameters), the compiler no longer
provides the default constructor for you.
Example: This program demonstrates the use of a default constructor, which is automatically called when an
object is created.

// Java Program to demonstrate


// Default Constructor
import java.io.*;

// Driver class
class Geeks{

// Default Constructor
Geeks() {
System.out.println("Default constructor");

// Driver function
public static void main(String[] args)
{
Geeks hello = new Geeks();
}
}
Output
Default constructor

Note: Default constructor provides the default values to the object like 0, null, false etc. depending on the type.

2. Parameterized Constructor in Java


A constructor that has parameters is known as parameterized constructor. If we want to initialize fields of the
class with our own values, then use a parameterized constructor.
Example: This program demonstrates the use of a parameterized constructor to initialize an object's attributes
with specific values.
// Java Program for Parameterized Constructor
import java.io.*;

class Geeks {

// data members of the class


String name;
int id;

Geeks(String name, int id) {


this.name = name;
this.id = id;
}
}
class GFG
{
public static void main(String[] args)
{
// This would invoke the parameterized constructor
Geeks geek1 = new Geeks("Sweta", 68);
System.out.println("GeekName: " + geek1.name
+ " and GeekId: " + geek1.id);
}
}
Output
GeekName: Sweta and GeekId: 68

Remember: Does constructor return any value?


There are no "return value" statements in the constructor, but the constructor returns the current class instance.
We can write 'return' inside a constructor.

3. Copy Constructor in Java


Unlike other constructors copy constructor is passed with another object which copies the data available from the
passed object to the newly created object.
Note: Java does not provide a built-in copy constructor like C++. We can create our own by writing a constructor
that takes an object of the same class as a parameter and copies its fields.
Example: This example, demonstrates how a copy constructor can be used to create a new object by copying
the values of another object's attributes.
// Java Program for Copy Constructor
import java.io.*;

class Geeks {

// data members of the class


String name;
int id;

// Parameterized Constructor
Geeks(String name, int id)
{
this.name = name;
this.id = id;
}

// Copy Constructor
Geeks(Geeks obj2)
{
this.name = obj2.name;
this.id = obj2.id;
}
}

class GFG {
public static void main(String[] args)
{
// This would invoke the parameterized constructor
System.out.println("First Object");
Geeks geek1 = new Geeks("Sweta", 68);
System.out.println("GeekName: " + geek1.name
+ " and GeekId: " + geek1.id);

System.out.println();

// This would invoke the copy constructor


Geeks geek2 = new Geeks(geek1);
System.out.println(
"Copy Constructor used Second Object");
System.out.println("GeekName: " + geek2.name
+ " and GeekId: " + geek2.id);
}
}

Output
First Object
GeekName: Sweta and GeekId: 68

Copy Constructor used Second Object


GeekName: Sweta and GeekId: 68

Constructor Overloading
This is a key concept in OOPs related to constructors is constructor overloading. This allows us to create multiple
constructors in the same class with different parameter lists.
Example: This example, demonstrates constructor overloading, where multiple constructors perform the same
task (initializing an object) with different types or numbers of arguments.
// Java Program to illustrate constructor overloading
// using same task (addition operation ) for different
// types of arguments
import java.io.*;

class Geeks {

// constructor with one argument


Geeks(String name)
{
System.out.println("Constructor with one "
+ "argument - String: " + name);
}

// constructor with two arguments


Geeks(String name, int age)
{

System.out.println(
"Constructor with two arguments: "
+ " String and Integer: " + name + " " + age);
}

// Constructor with one argument but with different


// type than previous
Geeks(long id)
{
System.out.println(
"Constructor with one argument: "
+ "Long: " + id);
}
}

class GFG {
public static void main(String[] args)
{
// Creating the objects of the class named 'Geek'
// by passing different arguments

// Invoke the constructor with one argument of


// type 'String'.
Geeks geek2 = new Geeks("Sweta");

// Invoke the constructor with two arguments


Geeks geek3 = new Geeks("Amiya", 28);

// Invoke the constructor with one argument of


// type 'Long'.
Geeks geek4 = new Geeks(325614567);
}
}
Output
Constructor with one argument - String: Sweta
Constructor with two arguments: String and Integer: Amiya 28
Constructor with one argument: Long: 325614567

Common Mistakes to Avoid


Some common mistakes to avoid when working with constructors in Java are listed below:
• Forgetting super() in Child Classes: Always call the parent constructor (super()) if the parent class
has no default constructor, or it will lead to compilation errors.
• Excessive Work in Constructors: Keep constructors simple and focused on initialization, avoiding
heavy logic that slows down object creation.
• Not Handling Null Checks: Always validate parameters to avoid NullPointerException when
constructing objects.
Constructor Overloading in Java

Last Updated : 16 Jun, 2023


Java supports Constructor Overloading in addition to overloading methods. In Java, overloaded constructor is called
based on the parameters specified when a new is executed.
When do we need Constructor Overloading?
Sometimes there is a need of initializing an object in different ways. This can be done using constructor overloading.

For example, the Thread class has 8 types of constructors. If we do not want to specify anything about a thread then
we can simply use the default constructor of the Thread class, however, if we need to specify the thread name, then
we may call the parameterized constructor of the Thread class with a String args like this:

Thread t= new Thread (" MyThread ");

Let us take an example to understand the need of constructor overloading. Consider the following implementation of
a class Box with only one constructor taking three arguments.

// An example class to understand need of


// constructor overloading.
class Box
{
double width, height,depth;

// constructor used when all dimensions


// specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}

// compute and return volume


double volume()
{
return width * height * depth;
}
}

As we can see that the Box() constructor requires three parameters. This means that all declarations of Box
objects must pass three arguments to the Box() constructor.

For example, the following statement is currently invalid:


Box ob = new Box();

Since Box() requires three arguments, it’s an error to call it without them. Suppose we simply wanted a box object
without initial dimension, or want to initialize a cube by specifying only one value that would be used for all three
dimensions. From the above implementation of the Box class, these options are not available to us. These types of
problems of different ways of initializing an object can be solved by constructor overloading.

Example of Constructor Overloading

Below is the improved version of class Box with constructor overloading.

// Java program to illustrate


// Constructor Overloading
class Box {
double width, height, depth;

// constructor used when all dimensions


// specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}

// constructor used when no dimensions


// specified
Box() { width = height = depth = 0; }

// constructor used when cube is created


Box(double len) { width = height = depth = len; }

// compute and return volume


double volume() { return width * height * depth; }
}

// Driver code
public class Test {
public static void main(String args[])
{
// create boxes using the various
// constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);

double vol;

// get volume of first box


vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);

// get volume of second box


vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);

// get volume of cube


vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
Output

Volume of mybox1 is 3000.0


Volume of mybox2 is 0.0
Volume of mycube is 343.0

Using this() in Constructor Overloading


this() reference can be used during constructor overloading to call the default constructor implicitly from the
parameterized constructor.
Below is the implementation of the above method:
// Java program to illustrate role of this() in
// Constructor Overloading
public class Box {
double width, height, depth;
int boxNo;

// constructor used when all dimensions and


// boxNo specified
Box(double w, double h, double d, int num)
{
width = w;
height = h;
depth = d;
boxNo = num;
}

// constructor used when no dimensions specified


Box()
{
// an empty box
width = height = depth = 0;
}

// constructor used when only boxNo specified


Box(int num)
{
// this() is used for calling the default
// constructor from parameterized constructor
this();

boxNo = num;
}

public static void main(String[] args)


{
// create box using only boxNo
Box box1 = new Box(1);

// getting initial width of box1


System.out.println(box1.width);
}
}
Output

0.0
As we can see in the above program we called Box(int num) constructor during object creation using only box
number. By using this() statement inside it, the default constructor(Box()) is implicitly called from it which will
initialize the dimension of Box with 0.

Note : The constructor calling should be first statement in the constructor body.
For example, the following fragment is invalid and throws compile time error.
Box(int num)
{
boxNo = num;

/* Constructor call must be the first


statement in a constructor */
this(); /*ERROR*/
}

Important points to be taken care of while doing Constructor Overloading


• Constructor calling must be the first statement of the constructor in Java.
• If we have defined any parameterized constructor, then the compiler will not create a default
constructor. and vice versa if we don’t define any constructor, the compiler creates the default
constructor(also known as no-arg constructor) by default during compilation
• Recursive constructor calling is invalid in Java.

FAQ in Constructor Overloading

1. Differentiate Constructors Overloading vs Method Overloading.


Answer:
Strictly speaking, constructor overloading is somewhat similar to method overloading. If we want to have different
ways of initializing an object using a different number of parameters, then we mus t do constructor overloading as
we do method overloading when we want different definitions of a method based on different parameters

Constructor Chaining In Java with Examples

Last Updated : 23 Jul, 2025


Constructor chaining is the process of calling one constructor from another constructor with respect to current
object.

One of the main use of constructor chaining is to avoid duplicate codes while having multiple constructor (by means
of constructor overloading) and make code more readable.

Prerequisite - Constructors in Java


Constructor chaining can be done in two ways:

• Within same class: It can be done using this() keyword for constructors in the same class
• From base class: by using super() keyword to call the constructor from the base class.

Constructor chaining occurs through inheritance. A sub-class constructor's task is to call super class's constructor
first. This ensures that the creation of sub class's object starts with the initialization of the data members of the
superclass. There could be any number of classes in the inheritance chain. Every constructor calls up the chain till the
class at the top is reached.
Why do we need constructor chaining?
This process is used when we want to perform multiple tasks in a single constructor rather than creating a code for
each task in a single constructor we create a separate constructor for each task and make their chain which makes
the program more readable.

Constructor Chaining within the same class using this() keyword:

// Java program to illustrate Constructor Chaining


// within same class Using this() keyword
class Temp
{
// default constructor 1
// default constructor will call another constructor
// using this keyword from same class
Temp()
{
// calls constructor 2
this(5);
System.out.println("The Default constructor");
}

// parameterized constructor 2
Temp(int x)
{
// calls constructor 3
this(5, 15);
System.out.println(x);
}

// parameterized constructor 3
Temp(int x, int y)
{
System.out.println(x * y);
}

public static void main(String args[])


{
// invokes default constructor first
new Temp();
}
}
Output:
75
5
The Default constructor

Rules of constructor chaining :


1. The this() expression should always be the first line of the constructor.
2. There should be at-least be one constructor without the this() keyword (constructor 3 in above
example).
3. Constructor chaining can be achieved in any order.

What happens if we change the order of constructors?


Nothing, Constructor chaining can be achieved in any order
// Java program to illustrate Constructor Chaining
// within same class Using this() keyword
// and changing order of constructors
class Temp
{
// default constructor 1
Temp()
{
System.out.println("default");
}

// parameterized constructor 2
Temp(int x)
{
// invokes default constructor
this();
System.out.println(x);
}

// parameterized constructor 3
Temp(int x, int y)
{
// invokes parameterized constructor 2
this(5);
System.out.println(x * y);
}

public static void main(String args[])


{
// invokes parameterized constructor 3
new Temp(8, 10);
}
}
Output:
default
5
80

NOTE: In example 1, default constructor is invoked at the end, but in example 2 default constructor is invoked at
first. Hence, order in constructor chaining is not important.

Constructor Chaining to other class using super() keyword :


// Java program to illustrate Constructor Chaining to
// other class using super() keyword
class Base
{
String name;

// constructor 1
Base()
{
this("");
System.out.println("No-argument constructor of" +
" base class");
}

// constructor 2
Base(String name)
{
this.name = name;
System.out.println("Calling parameterized constructor"
+ " of base");
}
}

class Derived extends Base


{
// constructor 3
Derived()
{
System.out.println("No-argument constructor " +
"of derived");
}

// parameterized constructor 4
Derived(String name)
{
// invokes base class constructor 2
super(name);
System.out.println("Calling parameterized " +
"constructor of derived");
}

public static void main(String args[])


{
// calls parameterized constructor 4
Derived obj = new Derived("test");

// Calls No-argument constructor


// Derived obj = new Derived();
}
}
Output:
Calling parameterized constructor of base
Calling parameterized constructor of derived

Note : Similar to constructor chaining in same class, super() should be the first line of the constructor as super
class's constructor are invoked before the sub class's constructor.
Alternative method : using Init block :
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.
Example 1:
class Temp
{
// block to be executed before any constructor.
{
System.out.println("init block");
}

// no-arg constructor
Temp()
{
System.out.println("default");
}

// constructor with one argument.


Temp(int x)
{
System.out.println(x);
}

public static void main(String[] args)


{
// Object creation by calling no-argument
// constructor.
new Temp();

// Object creation by calling parameterized


// constructor with one parameter.
new Temp(10);
}
}
Output:

init block
default
init block
10

NOTE: If there are more than one blocks, they are executed in the order in which they are defined within the same
class. See the ex.
Example :

class Temp
{
// block to be executed 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

You might also like