A cautionary tale about Java class inheritance – J029

by Aug 14, 2015




DeegeU Java Course

“A cautionary tale about Java class inheritance” 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 – A cautionary tale about Java class inheritance

Hi, I’m DJ Spiess. In Java you can use one type as a template for making another type. The new type inherits all the same behavior as the original type. This powerful tool in object oriented programming is called inheritance. Java class inheritance allows you to reuse existing type functionality, and let you make modifications in behavior as you see fit.

In this lesson I’m going to teach you how to use inheritance in your Java applications. We’ll talk about what is Java class inheritance, and we’ll go over some examples of inheritance. And we’ll end with a true story about how class inheritance goes horribly wrong.

What is Java class inheritance?

Think about a child. The child inherits attributes from the mom and dad. They might have the same hair color from their mom. They might pick up bad behaviors from their dad, like bad jokes. Java class inheritance is something similar. However, instead of two parents, a class can have only one parent.

Parent classes usually represent a more general concept. So a Toyota Prius is a child of a car. A chicken is a child of a bird. A button is a child of a UI control. In the car example, we can also have a Toyota Camary as a child of car. A parent can have multiple children, but a child class in Java can have only one parent.

When a Java class inherits from another class, we say it extends the superclass. The code for inheritance looks like this. We use the keyword extends between the child class we’re creating, and the parent class we’re extending, or inheriting. We use an arrow to show the direction of inheritance in our diagram. So what happens to classes that inherit from other classes in Java?

A child class in Java inherits everything from the parent. So if the parent has a method, the child class will have the same method. Any attributes in the parent also are copied to the child class. There is one difference though. A child can only use attributes and methods which are scoped protected or public. If the method or attribute is package or private scope, the child has no access to it.

Parent and child classes - A cautionary tale about Java class inheritance - Free Java Course Online - DeegeU

Parent and child classes

The parent’s protected or public methods and attributes are used as if they belonged to the class itself. The private methods and attributes cannot be used directly from the child class. They are invisible to the child class.

That doesn’t mean it cannot be used. Say we have a private variable in the parent. It cannot be accessed from the child class. However, if we have public getters and setters, we can modify the variable in the child class. We just can’t access it directly.

The way Java class inheritance works is, when we call a method in Java, Java will look in our current class for the method. If it’s not there, it will look at the parent class for the method. It will keep doing this until it finds the method to execute. If the method doesn’t exist, it won’t compile.

All Java classes start at the class Object. Object was a horrible name for a class, but it is what it is. Other languages have done this too. So when we use the word “Object” with a capital O, we mean the class Object. A lowercase “o” means an instance of a class. You might want to get in the habit of calling all instance objects with the lowercase “o” instances to avoid confusion.

The nine methods in Object are also available in every class. We get these methods for free through inheritance. We’ve used one a few times. The method toString() is in the Object class. So every class in Java can be converted to the same useless string. We’ll learn how to fix that in a later lesson.

What is an example of Java class inheritance?

I mentioned earlier that parent classes should be more general concepts than the child class. The Java class inheritance relationship between two classes denotes an is-a relationship. To mentally test if one class should be a child of another, we ask “is the child class a parent class”? Is a Prius a car? Is a chicken a bird? If we answer yes, that’s a candidate for inheritance. On the other hand, if we ask “is a spaceship a duck”, the answer is likely no.

Clock inheritance - A cautionary tale about Java class inheritance - Free Java Course Online - DeegeU

A clock hierarchy using Java class inheritance

Let’s take the concept of a clock. The clock has a method called getTime(). We could also define three child classes, DigitalClock, AtomicClock, and AnalogClock. All three children are examples of a clock. We can say a DigitalClock “is a” clock. All three children have the method getTime(). The difference is how they get the time. This is an important point.

Each clock has it’s own method of determining the time. The internal methods for calculating the time can be different, but the API to other classes is the same. How it works internally isn’t important. We could swap out one clock for another in our code, and the application should not know the difference. Inheritance abstracts how something is accomplished.

We can also add behavior the parent does not have. These methods and attributes are only available to the child class and it’s children. We’ll want to be careful using this. In our clock example, we can replace a Clock class with a DigitalClock class. We cannot replace a DigitalClock class with a Clock. The replacement only works one way. We also cannot use a DigitalClock where an AtomicClock is expected.

When Java class inheritance goes bad!

And on that subject I’ll leave you with a cautionary tale about Java class inheritance. In the 1990s, the Australian Air Force had a tactical simulator for their helicopters. When you fly over wildlife, in this case kangaroos, the animals might give your position away when you scare them. So in the simulator, they needed herds of kangaroos to scatter when you flew over them.

java class inheritance kangaroos - A cautionary tale about Java class inheritance - Free Java Course Online - DeegeU

When Java class inheritance goes bad!

The programmers jumped right on it. They realized that they had infantry sprites which already had this behavior. If you flew over infantry, they scattered. So the programmers decided to make kangaroo sprites a child class of infantry sprites.

When the programmers demonstrated their simulator to the American allies, the kangaroos scattered as designed when the helicopter was flown over them. Everyone was happy. High fives all around.

Then the kangaroos regrouped behind a hill and started firing rocket launchers at the helicopter. The developers learned a hard lesson about inheritance, and the Americans had a new found respect for Australian wildlife.

In the next lesson we’ll dive more into inheritance. See you then!

Hey! Thanks for watching the video. If you like what you’re seeing or have any questions, let me know in the comments or on DeegeU.com! New videos come out each week, so make sure you subscribe. You don’t want to miss a video! In fact, lets go watch another DeegeU video. See you there!

<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.

  • Jet Fighter – clayster2012
  • http://opengameart.org/content/jet-fighter
  • Family and DNA images from https://pixabay.com
  • Clipart from https://pixabay.com and https://openclipart.org/

Get the code

The complete video lesson list for this free online programming course can be found on the course syllabus page.

The source code for “How to override a method 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