What is constructor chain in java

What is constructor chain in java

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

What is constructor chain in java

  • Introduction to Java
  • The complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works – JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?
  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods
  • Access Modifiers in Java
  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java
  • Inheritance in Java
  • Abstraction in Java
  • Encapsulation in Java
  • Polymorphism in Java
  • Interfaces in Java
  • ‘this’ reference in Java

Источник

Understanding Constructor Chaining in Java with Examples & Implementation

In Java, Constructors can be understood as blocks of code used to initialise newly created objects. A constructor is similar to instance methods in Java. However, there is a crucial difference between Constructors and methods in Java – while methods have a return type, Constructors do not have any specific return type. Programmers often refer to Constructors as a special type of method in Java.

Constructors in Java have same name as the class, and they look like the following:

When a constructor is called from within another constructor, that is when Constructor Chaining occurs in Java. However, before we dive deeper into Constructor Chaining, let’s first have a quick look at how Constructors work in Java, along with some examples to solidify your understanding.

Читайте также:  Css fit content heights

How Do Constructors in Java Work?

To understand how Constructors work, let’s look at an example. Suppose we have a class named myProgram. Now, when we create the object of this class, we will have to write the following statement:

Ads of upGrad blog

myProgram obj = new myProgram()

As you can see, the new keyword used in the above example creates the object of myProgram and invokes a constructor to initialise this newly created object.

If this sounds a little confusing to you, fret not. Let’s look at a simple constructor program in Java to better understand the working of Constructors in Java.

Basic Constructor Program in Java

Look at the following piece of Java code that uses Constructors:

public class Test < String book; //Constructor Test()< this.book = "A Catcher in the Rye"; >public static void main(String[] args) < Test obj = new Test(); System.out.println(obj.book); >> Output: A Catcher in the Rye

In the above program, we have created an object named ‘obj’ of our class Program. Then, we printed the instance variable name of this newly created object. As you can see from the output, the output is the same as the value passed to ‘book’ during the Constructor’s initialization.

What this shows is that the moment the obj object was created, the Constructor got automatically invoked. Here, we used the ‘this’ keyword to refer to the current object. There are more ways to do this, too, which we will talk about later in the article while discussing Constructor Chaining.

With the basics of Constructor in Java settled, let’s move on to Constructor Chaining in Java and how it works!

Chaining of Constructors Within a Single Class

But what is constructor chaining in Java involving a single class? Calling one constructor from another in the same class includes constructor chaining within that class. The “this” keyword is used in the syntax for constructor chaining within the same class. The current class instance is referred to when “this” is used. It is best to understand the usage of constructor chaining in Java with example .

Chaining Constructors from Base/Parent Classes

A class in Java can derive from another class; the derived class is referred to as a subclass, and the class from which it derives is referred to as a superclass. A subclass can have its own constructors and invoke those of its superclass.

A superclass constructor uses the term super(), followed by the required inputs. The super() keyword must always be present in the subclass constructor’s first line.

Call from a Different Constructor, a Builder

Using the this() keyword, a constructor in Java can call another constructor from the same class. The first keyword in the constructor must always be the this() keyword, which can only be used to call another constructor of the same type.

Telephone Superclass Constructor

The super() keyword in Java allows subclass constructors to call the superclass’s constructor. The super() keyword, which can only be used to call the constructor of the subclass’s superclass, must always be the first line of the subclass constructor.

Java programs may behave differently if the constructors are arranged in a different sequence. If a class has many constructors and one of them uses the this() keyword to call another constructor, changing the order of the constructors can change how a program behaves.

Читайте также:  Image url to base64 java

A Different Way to Chain Constructors Using the Init Block

Using an initialisation block is another approach to constructor chaining in Java . A section of code known as an initialisation block runs before the constructor is called. The class’s instance variables can be initialised using this block.

Essentials of Constructor Chaining in Java

When we call a Constructor from another Constructor of the same class, what happens is known as Constructor Chaining. The primary purpose of doing Constructor Chaining is to pass parameters through a bunch of different constructors and only initialise them in one place. This way, you get a chance to maintain all of your initialisations in a single location while different constructors can be provided to the users.

If you don’t perform Constructor Chaining and two different Constructors require one parameter, you will need to initialise that parameter twice. Plus, every time the initialisation changes, you will need to make respective changes to all the constructors instead of just one.

As a rule of thumb, you should always call Constructors with more arguments from Constructors that have fewer arguments. You also must be aware that we can overload multiple Constructors in the class. However, at the time an object is created, only one particular Constructor gets called. There can be quite a few situations while programming in Java where you would need to call multiple constructors from one another without creating different objects. This mechanism of invoking one Constructor from another constructor and when that involved Constructor invokes another constructor is known as constructor chaining.

Learn Software Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

There are two primary things that you should keep in mind regarding Constructor Chaining to ensure utmost clarity:

  • The primary purpose of Constructor Chaining is to maintain the code. The idea is to help you write only one piece of code which can be reused across your program. This way, not only will your code be clean and readable, but it will also be a lot easier to manage with all the corrections and changes happening only to one location instead of all the Constructors.
  • The Constructor that has been invoked does not create a separate object. Instead, it uses the currently running object to invoke another constructor. It is just like calling a different method inside your Constructor, except it is also a constructor.

As you saw in the earlier example, we used this keyword to access the parameters of the Constructor. Likewise, Constructor Chaining also requires primarily two keywords. Here are those two keywords:

  • this – Its method representation calls a current class constructor.
  • super – Its method representation calls an immediate super or parent superclass constructor.

In addition, you should be aware of a couple of other important terms and definitions in terms of Constructor Chaining in Java:

  • Constructor Invocation: When you invoke a Constructor, and that Constructor gets successfully invoked, it is known as Constructor Invocation.
  • Constructor Execution: If on invoking Constructor, control starts executing the statements in the Constructor body. It is known as constructor execution.
Читайте также:  Два foreach в одном php

Key Rules of Constructor Chaining in Java

With the basics of Constructor Chaining settled, let’s look at some essential rules of working with Constructor Chaining in Java:

  • this() can only call the parameters belonging to the same Constructor.
  • super() can only call the immediate superclass Constructor.
  • this() and super() should be the first statement in the Constructor.
  • This () and super() can’t be used within the same Constructor since both individuals need to be first statements, which is not practically possible.
  • You cannot add this() in all the Constructors of the same class, as there should be at least one Constructor without this() statement.
  • The invoking and executing of Constructors in Java happens oppositely. So, if the Constructors were called in the order A, B, C, then the execution will be in the C, B, A order.

For example, here, we have two separate classes that are working by overloading different Constructors. We want to execute the constructors in 2, 1, 4, 3, 5 order.

Ads of upGrad blog

To execute constructors in order, we need to call the constructors exactly in opposite order like 5, 3, 4, 1, 2, see in the below example.

class Parent < Parent()// 1 < this("hello"); System.out.println("in Parent 0 arg constructor 1"); >Parent(String msg)// 2 < System.out.println("in Parent(String) constructor 2"); >> class Constructor extends Parent < Constructor()// 3 < this(10);// calling 5 number constructor System.out.println("in Constructor 0 arg constructor 3"); >Constructor(String msg)// 4 < super();//calling 1 number parent class constructor System.out.println("in Constructor(String msg) arg constructor 4"); >Constructor(int i)// 5 < this("hello");//calling 4 number constructor System.out.println("in Constructor(int i) constructor 5"); >// main() method public static void main(String[] args) < Constructor cobj = new Constructor(); // calling 3 number constructor >> Output: in Parent(String) constructor 2 in Parent 0 arg constructor 1 in Constructor(String msg) arg constructor 4 in Constructor(int i) constructor 5 in Constructor 0 arg constructor 3 Summing up all the concepts of Constructors and Constructor Chaining in Java with one final example: class Emp < public String EName; public int EEarnings; public String address; public Emp() < this("Rahul"); >public Emp(String name) < this(name, 140035); >public Emp(String name, int sal) < this(name, sal, "New Delhi"); >public Employee(String name, int sal, String add) < this.EName=name; this.EEarnings=sal; this.address=add; >void disp() < System.out.println("Name: "+EName); System.out.println("Salary: "+EEarnings); System.out.println("Address: "+address); >public static void main(String[] args) < Employee obj = new Employee(); obj.disp(); >> Output: Employee Name: Rahul Employee Salary: 140035 Employee Address: New Delhi

Conclusion

With that, we come to the end of this article. We hope this clarified your doubts on Constructor Chaining in Java and solidified your understanding further. At upGrad, we believe in helping students from around the globe reach their full potential and succeed in their careers. Our courses are designed keeping in mind both freshers and experienced professionals.

One such course is upGrad’s Job-linked PG Certification in Software Engineering , specifically designed for first-time job seekers. Check out the course content and get yourself enrolled today! Learn all the relevant Software Engineering skills like Java, DSA, OODAP, JavaScript, MERN, AWS, etc., from industry experts and leading professionals.

Источник

Оцените статью