Java Constructor Chaining – J034

by Oct 21, 2015




DeegeU Java Course

The “Java Constructor Chaining” video is part of a larger free online class called “Free Java Course Online”. You can find more information about this class on “Free Java Course Online” syllabus.

Transcript – Java Constructor Chaining

Hi everyone! In this tutorial, we are going to look at Java constructor chaining. If you remember in the last video we ran into problems initializing our class. We were setting the same starting yardline in every constructor in our football game. Our concern was if the rules to football changed again, we would need to check every Java constructor to make sure we were setting the value correctly.

We could set the value as a constant, which would reduce the number of places we need to refactor. That would be a good solution.

Let’s assume though we also have the requirement to play according to different football rules for different years. We need to calculate the correct starting position based on the year. That means a constant no longer works for us.

We’ll start by creating a method that provides the starting yardline for a given year. This will return the value we need to initialize our game class.

So now we can set the value, but we’re still not solving our problem. We are actually in a worse position. We could forget to update a constructor, and now in one place we’re using a constant and the other we’re using the method. What we really want to do is set the value in one place, only once.

What we need to do is call one constructor from another constructor. This is called constructor chaining. We’re chaining our constructors together, and calling each one in order before returning a created instance. We do that by using the this keyword as a method.

The this keyword looks for another constructor matching the argument list we provide. There are a few gotchas though.

If the parameter list does not match a constructor, our code will not compile.

And of course we cannot have multiple constructors with the same parameter list, even if the parameter names are different. Java wouldn’t let us do that even if we didn’t chain constructors.

The this keyword also only works with constructors for the current class. We cannot use it to call constructors in our super class. To do that, we’d use the super keyword to call the parent class.

When we do use it, it must be the first line in the constructor. We also cannot do this more than once, meaning you cannot call more constructors once you’ve called another constructor. You only get to call one.

And the big gotcha is we cannot chain constructors in a way to create a loop. Java won’t even let us compile constructors with a loop. We’ll get an exception.

When we create our constructor chain, we need to keep the chain in a straight line as much as possible. An inverted tree would work too, but that can get complicated for other developers to figure out if our tree gets too big.

Ultimately our constructor chain should end up at a single constructor. That constructor should be the only constructor responsible for returning an instance. We can create multiple independent chains, but that gets confusing too. Best practice is one chain, with one ending.

A classic pattern for chaining constructors is to perform one initialization step each time. The starting constructor sets everything to a default value. Then each constructor adds one bit of information based on it’s parameter. If we have a situation where the construction path is simple, or we would always have initialization values known in a particular order, chaining constructors works well.

Of course, there’s a slight problem with this. What if we have only three of five parameters? There’s no real good way to jump in the middle of the chain, or skip constructors. We’ll need another approach. In the next tutorial we’ll look at something called the builder pattern to solve our initialization order problem.

Thanks for watching! If you have any questions let me know in the comments. New videos come out every week, so make sure you subscribe. You don’t want to miss a video! If you’re trying to get to the deegeu.com website, it’s down for the next week for a site update. Videos will still be posted.

And with that, I’ll see you in the next tutorial!

<p><script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- DeegeU - Right Side -->
<ins class="adsbygoogle" style="display:inline-block;width:336px;height:280px" data-ad-client="ca-pub-5305511207032009" data-ad-slot="5596823779"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script></p>

Tools Used

  • Java
  • NetBeans

Media Credits

All media created and owned by DJ Spiess unless listed below.

  • Brick Background https://pixabay.com/

Music
Disco Lounge by Kevin MacLeod is licensed under a Creative Commons Attribution license (https://creativecommons.org/licenses/by/4.0/)
Source: http://incompetech.com/music/royalty-free/index.html?isrc=USUAN1100602
Artist: http://incompetech.com/

Get the code

The source code for “Are you ready to tackle the fizzbuzz test in Java?” can be found on Github. If you have Git installed on your system, you can clone the repository by issuing the following command:

 git clone https://github.com/deege/deegeu-java-intro.git

Go to the Support > Getting the Code page for more help.

If you find any errors in the code, feel free to let me know or issue a pull request in Git.

<h2>Don't miss another video!</h2> <p>New videos come out every week. Make sure you subscribe!<br><script src="//apis.google.com/js/platform.js"></script></p> <div class="g-ytsubscribe" data-channel="deegeu" data-layout="full" data-count="default"></div> <p></p>

Comments

comments

DJ Spiess

DJ Spiess

Your personal instructor

My name is DJ Spiess and I’m a developer with a Masters degree in Computer Science working in Colorado, USA. I primarily work with Java server applications. I started programming as a kid in the 1980s, and I’ve programmed professionally since 1996. My main focus are REST APIs, large-scale data, and mobile development. The last six years I’ve worked on large National Science Foundation projects. You can read more about my development experience on my LinkedIn account.

Pin It on Pinterest

Share This