New Feature: Playlist Center! Pick a topic and let our playlists guide the way.

Start learning with our library of video tutorials taught by experts. Get started

Java Essential Training
Illustration by

Understanding inheritance and polymorphism


From:

Java Essential Training

with David Gassner

Video: Understanding inheritance and polymorphism

In a previous video, I described the concept of encapsulation, one of the major concepts of object-oriented programming. There are two other concepts that you need to master to be a great object-oriented programmer, and they are named Inheritance and Polymorphism. I'll describe them here. Inheritance means that there's a relationship between classes in your application. An inheritance relationship lets you inherit or extend functionality from one class to another. In the world of C++ there is multiple inheritance.
Expand all | Collapse all
  1. 10m 8s
    1. Welcome
      1m 3s
    2. Is this course for you?
      5m 35s
    3. Using the exercise files
      3m 30s
  2. 31m 24s
    1. The history of Java
      5m 19s
    2. Java compilation and syntax
      8m 54s
    3. Understanding the principles of Java
      8m 28s
    4. Choosing a development environment
      8m 43s
  3. 19m 5s
    1. Installing Java on Windows
      6m 42s
    2. Installing Eclipse on Windows
      3m 19s
    3. Exploring Java on Mac OS X Leopard and Snow Leopard
      2m 27s
    4. Installing Java on Mac OS X Lion
      3m 27s
    5. Installing Eclipse on Mac OS X
      3m 10s
  4. 46m 10s
    1. Creating a Hello World application
      11m 7s
    2. Exploring the Eclipse IDE
      8m 55s
    3. Compiling and running from the command line
      8m 2s
    4. Passing arguments to the application
      8m 17s
    5. Using the Java API documentation
      4m 5s
    6. Memory management and garbage collection
      5m 44s
  5. 58m 57s
    1. Everything is an object
      5m 59s
    2. Declaring and initializing variables
      9m 15s
    3. Working with numbers
      8m 32s
    4. Converting numeric values
      6m 40s
    5. Understanding operators
      7m 58s
    6. Working with character values
      5m 14s
    7. Working with boolean values
      5m 13s
    8. Outputting primitive values as strings
      5m 33s
    9. Creating a simple calculator application
      4m 33s
  6. 53m 40s
    1. Writing conditional code
      5m 35s
    2. Using the switch statement
      8m 50s
    3. Repeating code blocks with loops
      7m 35s
    4. Creating reusable code with methods
      6m 31s
    5. Declaring methods with arguments
      5m 41s
    6. Overloading method names with different signatures
      5m 53s
    7. Passing arguments by reference or by value
      5m 35s
    8. Creating a more complex calculator application
      8m 0s
  7. 20m 30s
    1. Using the String class
      5m 44s
    2. Building strings with StringBuilder
      3m 34s
    3. Parsing string values
      3m 19s
    4. Working with date values
      7m 53s
  8. 20m 44s
    1. Understanding compile-time vs. runtime errors
      4m 5s
    2. Handling exceptions with try/catch
      4m 55s
    3. Throwing exceptions in methods
      2m 50s
    4. Using the debugger
      8m 54s
  9. 32m 22s
    1. Using simple arrays
      4m 47s
    2. Using two-dimensional arrays
      6m 17s
    3. Managing resizable arrays with ArrayList
      7m 14s
    4. Managing unordered data with HashMap
      6m 5s
    5. Looping through collections with iterators
      7m 59s
  10. 52m 2s
    1. Understanding encapsulation
      5m 59s
    2. Creating and instantiating custom classes
      8m 8s
    3. Organizing classes with packages
      6m 47s
    4. Creating and using instance methods
      6m 52s
    5. Storing data in instance variables
      6m 56s
    6. Using constructor methods
      5m 40s
    7. Managing instance data with getter and setter methods
      8m 26s
    8. Using class variables and Enum classes
      3m 14s
  11. 41m 15s
    1. Understanding inheritance and polymorphism
      9m 12s
    2. Extending custom classes
      9m 1s
    3. Overriding superclass methods
      3m 8s
    4. Casting subclass objects
      5m 3s
    5. Understanding interfaces and implementing classes
      4m 2s
    6. Creating your own interfaces
      4m 14s
    7. Using abstract classes and methods
      6m 35s
  12. 32m 17s
    1. Managing files with the core class library
      7m 46s
    2. Managing files with Apache Commons FileUtils
      7m 32s
    3. Reading a text file from a networked resource
      7m 52s
    4. Parsing an XML file with DOM
      9m 7s
  13. 17m 39s
    1. Creating your own JAR files
      4m 54s
    2. Understanding the classpath
      5m 2s
    3. Documenting code with Javadoc
      7m 43s
  14. 47s
    1. Goodbye
      47s

Watch this entire course now—plus get access to every course in the library. Each course includes high-quality videos taught by expert instructors.

Become a member
please wait ...
Java Essential Training
7h 17m Beginner Dec 14, 2011

Viewers: in countries Watching now:

Join author David Gassner as he explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more. This course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts.

Topics include:
  • Understanding the history and principles of Java
  • Installing Eclipse and Java
  • Compiling and running from the command line
  • Managing memory and performing garbage collection
  • Declaring and initializing variables
  • Writing conditional code
  • Building and parsing strings
  • Debugging and exception handling
  • Using simple arrays
  • Creating custom classes
  • Working with encapsulation, inheritance, and polymorphism
  • Managing files
  • Documenting code with Javadocs
Subjects:
Developer Programming Languages
Software:
Android Java Eclipse
Author:
David Gassner

Understanding inheritance and polymorphism

In a previous video, I described the concept of encapsulation, one of the major concepts of object-oriented programming. There are two other concepts that you need to master to be a great object-oriented programmer, and they are named Inheritance and Polymorphism. I'll describe them here. Inheritance means that there's a relationship between classes in your application. An inheritance relationship lets you inherit or extend functionality from one class to another. In the world of C++ there is multiple inheritance.

A single class can inherit functionality from multiple other classes but in Java, there is only single inheritance, each new class can extend or inherit functionality from only one other class. This actually makes it a lot easier to manage your code because if you've created an inheritance relationship and you run into a bug that bug can either be in the class you are working with or in the class that you inherited from, but the issue has to be somewhere in that very linear path. There are a number of ways to describe an inheritance relationship and they are just different vocabularies.

You'll hear some developers describe the relationship as a parent-child relationship, where the parent has the functionality and the child is inheriting. You will also hear the terms base and derived, where a base class has the functionality and the derived class is extending it. In the world of Java, the terms that are most commonly used are Superclass and Subclass. The Superclass has the functionality and the Subclass is extending the Superclass. And again, each subclass in Java can only have one Superclass, in fact even if you don't explicitly extend a class all of your classes are extending another class, a Superclass.

There is a special class named object with an uppercase O and this is at the top of the Java inheritance tree. If you don't explicitly inherit from some class, you're inheriting from object automatically, so that's Inheritance. Polymorphism is the last important term to understand. Polymorphism means that when there is an inheritance relationship between a Superclass and a Subclass you can deal with an object that's instantiated from the subclass either as its native type, the subclass or as it's inherited or to extend a type the Superclass.

To do this, you declare the object and instead of declaring the native data type you declare the Superclass type. If it's a class that you're instantiating by calling a constructor method, you call the constructor method from the subclass but you use the data type of the Superclass. When you've done that it becomes possible to take that object which you declared as the Superclass and pass it to any method that's expecting an instance of the Superclass. When you have an inheritance relationship this can give you enormous flexibility in designing your code.

Let's visualize an inheritance relationship. Let's imagine a class named Olive. Well there are many kinds of olives in the world and so you might declare a Superclass named Olive that has functionality that's common to all olives but then you might create multiple subclasses, each representing one particular kind of Olive. This is how we would diagram the relationship with an arrow pointing to the Superclass. That arrow means that the subclasses are extending the functionality of the Superclass.

The Superclass is olive and all the others are the subclasses. We call this single inheritance because each subclass can only have a single superclass, but as you can see, a superclass can have many subclasses. superclasses don't need any special code, any class can be a superclass. And all of the fields and methods of that class can be inherited, unless they're marked as private. You'll see that it's very common to set fields or data values as private in a class and methods of a superclass as protected or public.

Private means that only the superclass can deal with the field directly, protected means that a method can be called either by the superclass or by its subclasses, and public means that those methods can be called by anybody. Let's take a look at code of a sample superclass. This might be the class Olive, the class Olive might have a couple of fields or data values. I've declared a double value called volume and a Boolean value called crushed which is initially set to false. I have a method called getVolume and the logic of that method says if the value crush is true then return the volume and otherwise return zero.

This is using the ternary operator, a shortened conditional syntax. There is a protected method named setVolume, it's protected so that it can only be called by the class itself or its subclasses. And there is a public method named crush which basically says this Olive has been crushed. The fields or data values are marked as private only the superclass can deal with them directly. To get volume method which is a getter accessor method can be called by anybody in the application.

This setVolume method, the setter can only be called by the class itself and the subclass and the crushed method is declared as public. Now again this is just one way of designing the code, it follows some standard recommendations in Java by keeping private data private, but you could choose to do it differently. Now the subclasses that extend the superclass. In order to extend the superclass you declare the class in your Java file and you use the extends keyword and reference the superclass.

It might look like this, I'm placing my class into a package named olives and then I create the class named Kalamata and I use the extends keyword and then the superclass named Olive. The subclass implementation might have a lot of details but here's one small example. As the subclass is constructed, and its constructor method is called it would be responsible for setting its own volume or the amount of oil it's capable of producing. So within the constructor method Kalamata which matches the name of the class itself it calls this.setVolume(2).

SetVolume is a protected method, so the subclass can call it, but the actual data it's affecting is stored in the superclass, it's hidden from the rest of the application. Another subclass of the same superclass would call the setVolume method also but it would set its numeric volume differently. So now Liguria is saying, I can get five units of oil and Kalamata is saying, I can get two units of oil. They're both calling the same method, they're both using that same hidden data that's in the superclass, but they are determining what the actual value is.

When you go to the main class code, you can now say I'm going to declare an array of Olives. Olive, bracket, bracket, means multiple Olives. But then when you actually declare the instances of the object, you use the constructor methods of the individual subclasses. I have an array with two Kalamatas and one Liguria, but they're all olives because of the inheritance relationship. I could then create an instance in the OlivePress call to getOil method and within that method it would then go and call the appropriate methods of the olive object and for Kalamata's, it would get two units, for Liguria's it would get five units and so on.

The rest of the application does not need to know the mechanics of how the volume is being calculated. All the top-level application has to do is say, I've got these three olives and they're of these types, go ahead and crush them. The actual mechanics are hidden within the class implementations. This idea that you can create an instance of a class by referring to it uniquely named constructor method but then take the object and fit it into a data type of its superclass is polymorphism at work.

You're taking an object that has a native type in your saying I'm going to use it as though its supertype, that's polymorphic and it allows you to build really elegant applications Within the implementation of the OlivePress, it would simply loop through the olives and call the methods, it would get the oil, it would add that to the olive oil, and the end result would be a correct calculation. The OlivePress doesn't need to know how much oil you get out of each olive and it doesn't even need to know that they're all these different kinds of olives out there.

From the point of view of the OlivePress, there is only one kind of olive an Olive, and you can crush it and you can add it to the oil. The details are hidden within the implementation. So that's the idea of inheritance and polymorphism. In the rest of the videos of this chapter I'll show you how to implement inheritance and put it to work polymorphically in your applications, and then in a later chapter we'll go on to more advanced concepts using constructs called interfaces and abstract classes that also adds to the inheritance model of Java.

There are currently no FAQs about Java Essential Training.

 
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.
Upgrade now


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

join now Upgrade now

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Java Essential Training.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.