Java Class Inheritance
Java Class Inheritance
Written by Ian Elliot   
Monday, 24 September 2012
Article Index
Java Class Inheritance
Constructor & Inheritance


What if you inherit a function that doesn’t do the job that you want it to?

No problem, you simply override it!

(Not to be confused with overloading introduced earlier.)

If you create a new function with the same name and signature as an inherited one it is your new member function that wins out and will be used. That is the new overrides the old.

For example, Point.Swap() might be better defined, for strange geometric reasons, in PointColor as a function that swaps and negates each coordinate.  So let's override the version in Point with a new version in PointColor-

public void Swap() {
        int temp;
        temp = -X;
        X = -Y;
        Y = temp;

Now when you used PC.Swap() it is this new version in PointColorthat is used- but notice that when you use Current.Swap it is still the old version that is used on a point object.

The only problem is that this doesn’t work because X and Y are private data members and not even PointColor, a descendent of Point can get at them! A correct version of Swap would have to use the access functions just like any other function outside of the point class -

public void Swap() {
        int temp;
        temp = - getX();


An alternative would have been to weaken the protection of the private members to private protected - but more of this idea later.

It is also modern Java practice to add an annotation to an overridden method to make sure that you know that it overrides an inherited method:

       public void Swap() {
        int temp;
        temp = - getX();


Constructors and inheritance

Don’t read this unless you have understood inheritance and are happy with it!

There is an interesting little problem with inheritance and one that is usually ignored by most introductions, and even slightly advanced texts, on Java.

When you create a new class by inheritance what happens to the constructors?

After all the original or parent class might have a constructor defined which is essential to initializing its members but when you create an instance of the child class it is the child's constructor that is involved so how does the parent get initialized?

The answer to the problem of inherited constructors is that when an instance of the child class is created the system tries to call the default constructor of the parent and then calls the default constructor of the child class.

If there are explicit constructors, i.e. ones you have written, then things get more complicated. The system will first try to call the default constructor of the parent, i.e. one without parameters. If a parameterless constructor doesn’t exist then the system stops with an error message. If one does exist is then it carries on and uses it.

Now this only leaves the problem of what to do if the parent has a constructor with parameters and you actually want to use it?

The answer is that you include the call super(parameters) in the child's constructor. This calls the appropriate parent's constructor with the parameters as specified and stops the system calling the default.

This is complicated but consider the PointColor class introduced earlier. Its constructor should initialize all three  member variables X, Y and Color. Two can be initialized by the Point’s constructor -

PointColor(int X,int Y, int Color){

This results in the constructor Point(int,int) being called to set X and Y.  Of course if you have an inheritance chain the constructor calls work their way back to the mother of all classes…

Is Inheritance Bad?

When object oriented programming was first invented one of its main claims to be a better system of programming was inheritance. It allowed you to reuse code in a way that was much better than copy and paste reuse. For example, if you change the way the Point class is implemented those changes are inherited by the PointColor class. If you used copy and paste to create the PointColor class you would have to remember to edit it with the changes you made to Point.

Unfortunately over time programmers discovered that inheritance was a two edged sword. Any changes you make to Point propagate to PointColor and all of the classes that inherit from it or PointColor or any of its child classes. If this works then great. If it doesn't work then a change in the base class i.e. Point could stop derived classes working. As you can imagine the resulting bugs can be difficult to put right.

For this and many other reasons inheritance is not though of as the cure all it once was.

Today the motto is "prefer composition over inheritance". What this means is that you can often change your view slightly from IS A to HAS A. For example, PointColor IS A Point with a Color but you could also say PointColor HAS A Point and a Color. In this case you would create an instance of Point within the PointColor class - i.e. no inheritance. Creating objects that have other objects as properties is called composition or aggregation and it is a powerful but sometimes problematic technique. 

These are all advanced topics and we need to return to the theory of using classes and objects later. For the moment concentrate on the practice of creating and using them.

To Summarize

  • Objects sould keep their internal workings to themselves - they should encapsulate their workings. An object should offer the rest of the world a set of methods that allows the outside to work with it. For example, set and get methods rather than direct access to variables.
  • Constructors are used to initialize instances and they are called automatically when ever an instance is created.
  • You can overload a function by creating versions with different signatures - i.e. parameters. Which version of the function is called depends on the parameters you supply.
  • Object often have relationships which can be summed up by use fo the phrase "IS A". So a point with color IS A point but with some extra properties and methods.
  • A class A, the child or derived class,  that inherits from class B the parent or base class, has all of the properties and methods of B.
  • You can add methods and properties to augment those inherited and you can override inherited methods with new methods.
  • You can call the base class' constructor within the child's constructor.
  • Inheritance was thought to be a cure all solution but today it is used with caution and only when there are clear benefits.


Modern Java
With NetBeans And Swing



  1. Getting started with Java

    In chapter 1 we tell you how to get started with modern Java development in the shortest possible time. The approach uses NetBeans and Swing and all of the resources used are free to download and use.

  2. Introducing Java - Swing Objects
    In the second chapter of our beginner's guide to Modern Java we find out more about objects by exploring the Swing framework with a simple hands-on example.

  3. Writing Code

    Using ifs and loops is one of the most difficult parts of learning how to program. Our beginners introduction to Java reaches the part all programmers have know and know well - how to write code.

  4. Command Line Programs
    Command line programming means doing things in the simplest possible way. We take a careful look at how data types and code build a program.

  5. User Interface - More Swing
    Finding out how to create a User Interface (UI) using the Java Swing library is not only a useful skill, it also is an ideal way to learn about objects and to make sure that the ideas really have sunk in.

  6. Working With Class
    The Swing components have provided an easy approach to the idea of objects, but there comes a time when you have to find out how to create your own. In this part of Modern Java, we look at the standard ideas of object-oriented programming.

  7. Java Class Inheritance
    Working with classes and objects is a very sophisticated approach to programming. You can't expect to absorb all of its implications in one go. We have already looked at the basics of class and objects. Now we need to look at encapsulation, constructors, overloading and inheritance.

  8. Building a Java GUI - Containers
    In this chapter we get to grips with the idea of a container that is used to host components to build a user interface. We also find out how the Swing GUI Builder generates code to make it all much easier. 

  9. Java Data Types - Numeric Data
    After looking at some of the advanced ideas of classes and objects we need to return to some simpler topics to make our understanding complete. We need to look more closely at data and, to get things moving, numeric data. 




To be informed about new articles on I Programmer, install the I Programmer Toolbar, subscribe to the RSS feed, follow us on, Twitter, Facebook, Google+ or Linkedin,  or sign up for our weekly newsletter.


blog comments powered by Disqus

Last Updated ( Thursday, 09 June 2016 )

RSS feed of all content
I Programmer - full contents
Copyright © 2016 All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.