Vous êtes sur la page 1sur 6

7/19/2018 Constructor Chaining in Java with Example programs | Scientech Easy

Scientech Easy

Home About Us Contact Privacy Policy Contact Us    

SCIENTECH EASY 01

02
Blood Test Types

Compatibility Test Online



03

04
Testing Laboratory

Software Testing Tools

H OME CORE JAVA SELENIUM GENERAL SCIENCE GK

GENERAL KNOWLEDGE TOPIC/SYLLABUS GENERAL SCIENCE TOPIC/SYLLABUS INDUSTRIAL CORE JAVA TOPIC/SYLLABUS SELENIUM AUTOMATION TESTING SYLLABUS

Home / Core Java / Constructor Chaining in Java with Example programs


01 Create Your Own Website

Constructor Chaining in Java with Example programs 02 Java Coding Course


by Scientech Easy on July 16, 2018 in Core Java

Welcome to Java online tutorial point. In this tutorial, We will learn a very interesting and important topic 03 Java Programs For Practice

Constructor chaining in Java with example and programs in easy and step by step like a Pro. It's an easy
04 Java Beginner Tutorials
topic if you do it smart.

05 Java Programming Training


Constructor Chaining in Java
First of all, we understand the definition of chaining in Java. The definition of Chaining in Java is " a set of links
which connect one constructor to another constructor." Thus, we can define Constructor chaining as "
LABELS
Constructor chaining is a technique of calling one constructor from another constructor using "this()" and
"Super()" keyword. When you will use constructor chaining, it is important to understand the order in which the  CORE JAVA
constructor will execute. The constructor chain is followed until it reaches the last chained constructor and the end
 GENERAL KNOWLEDGE TOPIC/SYLLABUS
of the chain will always be object's class constructor because of the inheriting every class from the object class by
 GENERAL SCIENCE MCQ
default.
Now see the below image which shows that a class College with three constructors in which first we called the two  GENERAL SCIENCE TOPIC/SYLLABUS

parameter constructor after that one parameter constructor called using this(parameters) keyword and then called  GK
the default constructor. That's order of execution. You can also change the order as you like. Therefore, it is
 INDUSTRIAL CORE JAVA TOPIC/SYLLABUS
important to understand the order of execution of the constructor that which constructor has to execute first and
 SELENIUM
last?
 SELENIUM AUTOMATION TESTING SYLLABUS

01 Create Your Own Website

02 Java Coding Course

03 Java Programs For Practice

04 Java Beginner Tutorials

05 Java Programming Training

RE CE NT POPULAR

Constructor Chaining in Java with


Constructor Chaining in Java Example programs
 Scientech Easy  Jul 16, 2018
You cannot call the constructor directly by name because it is illegal in Java.
Java Constructor overloading Tutorial
Why do we use/need Constructor chaining in Java? with Program
 Scientech Easy  Jul 11, 2018

https://www.scientecheasy.com/2018/07/constructor-chaining-java-example-program.html 1/6
7/19/2018 Constructor Chaining in Java with Example programs | Scientech Easy
Constructor chaining is used where you want to perform multiple tasks in a separate constructor for each task and Basic Core Java Tutorial Point Step By
make their order by chaining which makes the program more readable and easy to understand for everyone. You Step
 Scientech Easy  Jul 06, 2018
can provide as many as constructors as you want in your classes and use constructor chaining to set the link among
them. Java Constructor: Default &
Parameterized with Example
How to call one Constructor from another constructor?   Scientech Easy  Jul 03, 2018

To call one constructor from another constructor is called Constructor chaining and it can be Memory allocation of Primitive & Non-
implemented in two ways: primitive Data Type
1. Using this() keyword to call the current class constructor within "same class".  Scientech Easy  Jun 30, 2018

2. Using super() keyword to call the Super class constructor from the "base class".
Let's see one by one.
Blogging tips 2018

this() Constructor Call


If you need to call the same or current class constructor within the same class, you will have to use this() Keyword.
The syntax to call the same class constructor are:
this(), or this(ParamterList)
The statement this(parameters) invokes the same class constructor with parameters which must match.
For example:
this(); ➨ To call default current class constructor.
this("name"); ➨ To call one parameter current class constructor with String argument.
this("shubh", 24) ➨ To call two parameters current class constructor with String and int argument.
Caution:
➲ You must use the this () keyword to call the current class constructor because JVM never puts automatically this()
keyword like super() keyword.

Super and this keyword

➲ this() keyword must be in the first line of the constructor to call the same class constructor or current class
otherwise you will get this error message: Exception in thread "main" java.lang.Error: Unresolved
compilation problem: Constructor call must be the first statement in the constructor.

Note:
➲ There must be at least one constructor without this keyword.
➲ Constructor chaining can be done in any order.

Let's see a very simple example step by step.


Program Source Code 1:

package scientecheasy;

public class Developed {


// Declaration of Default Const.
Developed(){ (Line 6)
System.out.println("Java was developed by James Gosling"); // (Line 7)
}
// Declaration one parameter const.
Developed(int year){ (Line 2)

// Declaration of this keyword with two parameters list. Must be the first line. Don't forget.
this("Java" , 1995); // It will call two parameter const. of same class. (Line 3)
System.out.println("James Gosling is known as Father of Java programming language.");
} // (Line 9)

https://www.scientecheasy.com/2018/07/constructor-chaining-java-example-program.html 2/6
7/19/2018 Constructor Chaining in Java with Example programs | Scientech Easy
// Declaration of two parameters const.
Developed(String name, int year){ (Line 4)

// Declaration of this keyword without the parameter.


this(); // It will call default const. due to no parameter in this() keyword. (Line 5)

System.out.println("at Sun Microsystem and released in 1995"); // (Line 8)


}

// Method Declaration.
void display(){
System.out.println("The Java compiler is written in Java but Java runtime in ANSI C.");
} //
// Static method or main method.
public static void main(String[] args) {

// Create the object of class Developed using the new keyword and passes the integer value from const.
Developed obj=new Developed(1995);// It will call one parameter const. (Line 1)

// Call display method using object reference variable obj.


obj.display();
}

Output:
Java was developed by James Gosling
at Sun Microsystem and released in 1995
James Gosling is known as Father of Java programming language.
The Java compiler is written in Java but Java runtime in ANSI C.

Execution Process:
Line 1 ➨ Line 2 ➨ Line 3➨ Line 4 ➨ Line 5 ➨ Line 5 ➨ Line 6 ➨ Line 7 ➨ Line 8 ➨ Line 9 and so on.
We hope that this execution process will help to understand the flow of execution of the program.

Program Source Code 2:

package protien;

public class Protein {


// Declaration of Encapsulated Instance Variable.
private String gender;
private int need;
private String source;

Protein(){
this("female" ,46);// it will call two parameter const.
System.out.println("Protein requirement for children above 9 years old: 36 gm/day");

Protein(String s, int need){


this("male" , 56 , "milk");// It will three parameter const.
System.out.println("Protein requirement for women: 46 gm/day");
}

Protein(String gender, int need, String source){


this.gender=gender;
this.need=need;
this.source=source;
System.out.println("Protein requirement for men: 56 gm/day");
}
}

package protein;

public class ProteinTest {

public static void main(String[] args) {


//Create three objects with different parameters in the constructor.
Protein p1=new Protein();// will call default const.
Protein p2=new Protein("female",46); // will call two parameters const.
Protein p3=new Protein("male", 56, "milk"); // will call three parameters const.

}
}

Output:
Output after creating the first object
Protein requirement for men: 56 gm/day
Protein requirement for women: 46 gm/day
Protein requirement for children above 9 years old: 36 gm/day

Output after creating the 2nd object.


Protein requirement for men: 56 gm/day
Protein requirement for women: 46 gm/day

https://www.scientecheasy.com/2018/07/constructor-chaining-java-example-program.html 3/6
7/19/2018 Constructor Chaining in Java with Example programs | Scientech Easy

Output after creating the 3rd object.


Protein requirement for men: 56 gm/day

super() Constructor Call


If you need to call superclass constructor from the subclass constructor then you will have to use super() keyword
in the subclass constructor. The syntax to call a superclass constructor is:
super(), or super(Parameterlist).
The statement super() calls the no-argument constructor of its superclass and the super(argument) invokes the
superclass constructor where argument must match.
For example:
super(); ➨ To call default superclass const.
super(24); ➨ To call the superclass constructor with one int parameter.
Caution:
➲ You must use super() keyword to call the superclass constructor but if you do not put a super keyword, JVM will
put automatically the super() keyword.
➲ super() keyword must be in the first line of the constructor. Calling a superclass constructor' name in a subclass
causes a syntax error.

Note:
➲ A constructor is used to create the object of the class. Unlike properties and method, the constructor of the
superclass is not inherited in the subclass. They can only be called from the subclass constructor using the super
keyword. (always Remember it).
Let's take one simple example to understand all the points.

Program Source Code 3:

package scientecheasy;

public class School {


// Declare the instance variable.
String stName;
int stRoll;
int stId;

// Declares one parameter const.


School(String schoolName){ (Line 8)
this(2); // calls one parameter const. with int within same class. (Line 9)
System.out.println("Student's Detail: "); (Line 12)
}
School(int s){ (Line 10)

System.out.println("Delhi Public School"); (Line 11)


}
// Declares three parameters const.
School(String stName, int stRoll, int stId){ (Line 6)
this("DPS");// calls one parameter const. with String parameter within same class. (Line 7)
this.stName=stName;
this.stRoll=stRoll;
this.stId=stId;
}
void display(){
System.out.println("Name: " +stName);
System.out.println("Roll no. : " +stRoll);
System.out.println("Id: " +stId);

}
}

package scientecheasy;

public class Student extends School{ // extends is used for developing inheritance between two classes.
// Declares default const.
Student(){ (Line 4)
super("Shubh" , 2 , 2345);// calls superclass const. with three parameters. (Line 5)
}
Student(String schoolName){ (Line 2)
this(); (Line 3)
}

public static void main(String[] args) {


// Create the object of the class School and passes String value within double quotes from const.
Student st=new Student("DPS"); // calls one parameter const. of same class. (Line 1)
st.display();
}

https://www.scientecheasy.com/2018/07/constructor-chaining-java-example-program.html 4/6
7/19/2018 Constructor Chaining in Java with Example programs | Scientech Easy

Output:
Delhi Public School
Student's Detail:
Name: Shubh
Roll no. : 2
Id: 2345

Execution Process:

Line 1 ➨ Line 2 ➨ Line 3 ➨ Line 4 ➨ Line 5 ➨ Line 6 ➨ Line 7 ➨ Line 8 ➨ Line 9 ➨ Line 10 ➨ Line 11 ➨ Line 12 and so
on.
Program Source code 4:

package Nutrition;

public class Proteins {


Proteins(){ // Superclass const.
System.out.println("Protein is one of the basic building blocks of the Human body. ");
System.out.println("Hair, Skin, Eyes, Muscles, and organs are all made up of Protein");
}

package Nutrition;

public class Source extends Proteins {


Source(){
this(1); // Calls one parameter const. of same class.
System.out.println("Source of Proteins are milk, eggs, meat, pulses, soybeans");
}
Source(int s){

// Here, we will not place any super()keyword.


// JVM will automatically put the super() keyword and call superclass const.
System.out.println("Proteins are made up of amino acids");
}
}

package Nutrition;

public class MyProtein {


public static void main(String[] args) {
Source sc=new Source(); // Calls default const. of class Source.
}
}

Output:
Protein is one of the basic building blocks of the Human body.
Hair, Skin, Eyes, Muscles, and organs are all made up of Protein
Proteins are made up of amino acids
Source of Proteins are milk, eggs, meat, pulses, soybeans

Final Words:
I hope that this tutorial will help you to understand the concept of Constructor Chaining in Java with an
Example program in an easy way and step by step. Basically, concepts are important.
                                                                                                                    Scientech Easy lov es you
                                              

Tags # Core Java      

About Scientech Easy


Scientech Easy provides online tutorials for Core Java, Selenium, General science and GK
Quiz with great questions for the competitive exam SSC, RRB.

RELATED POSTS:

Const ruct or Chai ni ng i n J av a wi t h J av a Const ruct or ov erl oadi ng J av a Const ruct or: Defaul t & Memory al l ocat i on of P ri mi t i v e &
Ex ampl e programs Tut ori al wi t h P rogram P aramet eri zed wi t h Ex ampl e Non-pri mi t i v e Dat a Ty pe

https://www.scientecheasy.com/2018/07/constructor-chaining-java-example-program.html 5/6
7/19/2018 Constructor Chaining in Java with Example programs | Scientech Easy

01 Java Course ➜

02 Java Beginner Tutorials ➜

Follow Us Facebook

 Facebook Scientech Easy


13 likes

Follow @Dgupta008

Liked Send Message

You and 4 other friends like this

Designed with  by TemplatesYard | Distributed by Blogspot Themes

https://www.scientecheasy.com/2018/07/constructor-chaining-java-example-program.html 6/6

Vous aimerez peut-être aussi