You are on page 1of 11

Tutorials

Student
Jobs
Courses
Search...
Sign In
Sign In
Home
Courses
Algorithms
Data Structures
Languages
Interview Corner
GATE
CS Subjects
Student
Jobs
GBlog
Puzzles
What's New ?
Related Articles
Related Articles
Basics
expand_more
Java Programming Language
Introduction to Java
Setting up the environment in Java
Java Basic Syntax
Beginning Java programming with Hello World Example
Command Line arguments in Java
How JVM Works – JVM Architecture?
Differences between JDK, JRE and JVM
Java Identifiers
Data types in Java
Variables in Java
Comments in Java
Operators in Java
Ways to read input from console in Java
Flow Control
expand_more
Decision Making in Java (if, if-else, switch, break, continue, jump)
Loops in Java
Java For loop with Examples
For-each loop in Java
Java while loop with Examples
Switch Statement in Java
Continue Statement in Java
Break statement in Java
Strings
expand_more
Strings in Java
String class in Java | Set 1
StringBuffer class in Java
StringBuilder Class in Java with Examples
Arrays
expand_more
Arrays in Java
Multidimensional Arrays in Java
Jagged Array in Java
Array Copy in Java
How to convert an Array to String in Java?
How to compare two arrays in Java?
Methods
expand_more
Methods in Java
Parameter Passing Techniques in Java with Examples
Returning Multiple values in Java
Different ways of Method Overloading in Java
Scope of Variables In Java
Constructors
expand_more
Constructors in Java
Copy Constructor in Java
Constructor Overloading in Java
Constructor Chaining In Java with Examples
Private Constructors and Singleton Classes in Java
OOP Concepts
expand_more
Classes and Objects in Java
Inheritance in Java
Encapsulation in Java
Polymorphism in Java
Abstraction in Java
Overriding in Java
Overloading in Java
Exception Handling
expand_more
Exceptions in Java
Types of Exception in Java with Examples
Checked vs Unchecked Exceptions in Java
throw and throws in Java
User-defined Custom Exception in Java
Interfaces & Abstract Classes
expand_more
Interfaces in Java
Nested Interface in Java
Marker interface in Java
Abstract Classes in Java
Difference between Abstract Class and Interface in Java
Functional Interfaces In Java
Comparator Interface in Java with Examples
Collections
expand_more
Collections in Java
Collections Class in Java
Collection vs Collections in Java with Example
Java | Implementing Iterator and Iterable Interface
List Interface in Java with Examples
ArrayList in Java
Vector Class in Java
Stack Class in Java
LinkedList in Java
Queue Interface In Java
PriorityQueue in Java
Deque interface in Java with Example
ArrayDeque in Java
Set in Java
HashSet in Java
LinkedHashSet in Java with Examples
SortedSet Interface in Java with Examples
NavigableSet in Java with Examples
TreeSet in Java
Map Interface in Java
HashMap in Java with Examples
Hashtable in Java
LinkedHashMap in Java
SortedMap Interface in Java with Examples
TreeMap in Java
Multithreading
expand_more
Multithreading in Java
Lifecycle and States of a Thread in Java
Main thread in Java
Java Thread Priority in Multithreading
Synchronized in Java
File Handling
expand_more
File Handling in Java with CRUD operations
Java.io.InputStream Class in Java
Java.io.OutputStream class in Java
Java.io.File Class in Java
File Permissions in Java
Copying file using FileStreams in Java
Delete a file using Java
Constructor Chaining In Java with Examples
Difficulty Level : Easy
Last Updated : 23 Aug, 2019
Prerequisite – Constructors in Java
Constructor chaining is the process of calling one constructor from another
constructor with respect to current object.
Constructor chaining can be done in two ways:

Within same class: It can be done using this() keyword for constructors in same
class
From base class: by using super() keyword to call 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 creation of sub class’s
object starts with the initialization of the data members of the super class. There
could be any numbers of classes in inheritance chain. Every constructor calls up
the chain till 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 same class using this() keyword :

Constructor Chaining In Java

filter_none
edit
play_arrow
brightness_4
// 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 :

The this() expression should always be the first line of the constructor.
There should be at-least be one constructor without the this() keyword (constructor
3 in above example).
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

filter_none
edit
play_arrow

brightness_4
// 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 :

filter_none
edit
play_arrow

brightness_4
// 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:

filter_none
edit
play_arrow
brightness_4
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 arguemnt.


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 :

filter_none
edit
play_arrow

brightness_4
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
This article is contributed by Apoorva singh. If you like GeeksforGeeks and would
like to contribute, you can also write an article using
contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.
See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Attention reader! Don’t stop learning now. Get hold of all the important Java
Foundation and Collections concepts with the Fundamentals of Java and Java
Collections Course at a student-friendly price and become industry ready.

RECOMMENDED ARTICLES
Page :
1
2
3
Method Chaining In Java with Examples
15, Jan 20
Implementing our Own Hash Table with Separate Chaining in Java
08, May 16
Java Program to Implement Hash Tables Chaining with Doubly Linked Lists
18, Jan 21
Constructor getAnnotatedReturnType() method in Java with Examples
25, Nov 19
Constructor getAnnotatedReceiverType() method in Java with Examples
25, Nov 19
Constructor equals() method in Java with Examples
25, Oct 19
Constructor getDeclaringClass() method in Java with Examples
25, Oct 19
Constructor getName() method in Java with Examples
25, Oct 19
Constructor toGenericString() method in Java with Examples
28, Oct 19
Constructor toString() method in Java with Examples
28, Oct 19
Constructor isVarArgs() method in Java with Examples
28, Oct 19
Constructor isSynthetic() method in Java with Examples
28, Oct 19
Constructor hashCode() method in Java with Examples
28, Oct 19
Constructor getParameterCount() method in Java with Examples
28, Oct 19
Constructor getGenericParameterTypes() method in Java with Examples
28, Oct 19
Constructor getDeclaredAnnotations() method in Java with Examples
28, Oct 19
Constructor getGenericExceptionTypes() method in Java with Examples
28, Oct 19
Constructor getAnnotation() method in Java with Examples
26, Nov 19
Constructor getParameterAnnotations() method in Java with Examples
26, Nov 19
Constructor getTypeParameters() method in Java with Examples
27, Nov 19
Constructor newInstance() method in Java with Examples
27, Nov 19
Default constructor in Java
04, Nov 10
Copy Constructor in Java
22, Nov 11
Constructor Overloading in Java
22, Mar 17

favorite_border
Like
0
first_page
Previous
Sort a string according to the order defined by another string
Next
last_page
Find the prime numbers which can written as sum of most consecutive primes
Article Contributed By :
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Vote for difficulty
Current difficulty : Easy
Easy
Normal
Medium
Hard
Expert
Improved By :
vkbvipul
Vikramaditya Kukreja
nidhi_biet
Article Tags :
Java
School Programming
Practice Tags :
Java
Improve Article
Report Issue
WHAT’S NEW
Data structures and algorithms - self placed
Data Structures and Algorithms – Self Paced Course
View Details

Ad-Free Experience - GeeksforGeeks Premium


Ad-Free Experience – GeeksforGeeks Premium
View Details

MOST POPULAR IN JAVA


Arrays.sort() in Java with examples
Split() String method in Java with examples
Reverse a string in Java
How to iterate any Map in Java
Initialize an ArrayList in Java

MOST VISITED IN SCHOOL PROGRAMMING


Arrays in C/C++
Reverse a string in Java
Python Dictionary
Inheritance in C++
C++ Data Types

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.

Load Comments
GeeksforGeeks
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org
Company
About Us
Careers
Privacy Policy
Contact Us
Learn
Algorithms
Data Structures
Languages
CS Subjects
Video Tutorials
Practice
Courses
Company-wise
Topic-wise
How to begin?
Contribute
Write an Article
Write Interview Experience
Internships
Videos
@geeksforgeeks , Some rights reserved
We use cookies to ensure you have the best browsing experience on our website. By
using our site, you acknowledge that you have read and understood our Cookie Policy
& Privacy Policy
Got It !
Lightbox

You might also like