BFOIT

Introduction
to Programming

Java

Extending Existing Classes
Inheritance


Introduction

Java is an Object-Oriented programming language.  In this lesson we learn about one of the key concepts of object-oriented programming: inheritance.


Specialization Comes to Programming

Let's say we want to get into the business of building a new MP3-player.  A quick look at one tells us we're going to need to build a plastic case, it's going to need an LCD display, a few buttons, a jack for the headphones; oh, and we need the headphones too.  If we pop one open and look inside we'll see we need to design a processor chip, some digital-to-analog stuff; wow - there's lots of components on the little motherboard inside...  This is going to take us a very long time to design and build...

Is this the way to make something these days?

Of course not!

Look all around you.  The chefs in restaurants don't catch their own fish, grow their own vegetables.  A carpenter doesn't chop down trees to make lumber and forge his own nails.  One of the criteria in common definitions of "civilization" is a complex division of labor - specialization.  And we started down this path over 5000 years ago.

To build our MP3-player, we would outsource much of the stuff we need to do.  What we have is an idea about how to make our player more attractive to teens; our creativity is our added value.  We would write the software that is in the player; we would let electronic manufacturers world-wide submit proposals to us to build the actual devices for us.  And, since we would use Java, we wouldn't even need to start our programming effort on low-level basics.

For the first few decades of computer programming, programmers did just this.  They would write their own small realtime operating system that interfaced higher-level software to the input/ouput devices.  This is no longer the case for Java applications and applets.  To write a new Java program like the one we would need, we would take advantage of functionality that already exists in Java's Virtual Machine and its rich library of existing classes.  We would combine the existing stuff with own Java source code.


Inheritance in Object-Oriented Programming

The fastest way to get something done in Java is to find an existing class that does almost what you want and you extend it.  If you want to add an applet to a web page you've authored, there's a class called "Applet" that you can extend.  If you want your Java application to open up a window on the screen you write a class that extends the class "Frame" provided in the Java Abstract Window Toolkit (AWT).  By extending something else you automatically get everything that it has.  You get this through a mechanism known in programming language jargon as inheritance; you inherit all of the things that make up the class you extend.

A good way to think about the Java extends feature and inheritance in general is to think of it as the sheets of transparent plastic that you write on when using an overhead projector.  When you put one on top of another, you see all that lies on the lower sheets - it all comes right through.  You get what's below the new sheet and everything that's on the new sheet.

Figure 18.1

Let's take advantage of inheritance to write a program similar to the one we have already written, but this one will create its own window.


Using "extends" to Create a Window-based Application

Let's create a window-based application.  I've said that all we need to do is build upon a class called Frame.  But, Frame objects are not quite complete by themselves; you need to add a windowListener object to them to handle an Event that occurs when the window is closed.

You already know a bit about events; that's how you received input from a user in TurtleTalk.  You learned how to handle both mouseclick events and keypressed events. But, handling events in Java is a little more work than in TurtleTalk, so I'm going to hide this from you at first.

Also, the easiest way to display centered text in a Frame is to first create another object (an AWT Label object) with our text in it.  Then, this object is put into the Frame.  So, I'm going to do this for you too.

I've created a class called "ExtendsStuff" that extends Frame and does all the stuff you haven't learned about yet.  It has a method called printInWindow( ) which can be used much like the way you used System.out.println( ).

So, how do you use printInWindow( )?  What changes need to be made to the hello.java source code?  Before I cover the changes, let's get a base to work from.  Take a few minutes and write a class with the name: "HelloWindow".

Go back and review Figure 17.3 if you are having problems.  In the body of main( ), invoke printInWindow( ) instead of System.out.println( ).  Try to do this on you own before reading any further.

Ok, what does your program look like?  My guess is that you came up with a file called HelloWindow.java that contains something that looks like:


    class HelloWindow
    {

        public static void main (String[] args)    
        {
            printInWindow("Hello World!");
        }

    } //end class HelloWindow
    
Figure 18.2

If you did, congratulations!  This is what you should have learned so far.  But, you need to learn a couple of new things to fix this, to get it to work.  If you went ahead and compiled this source code, you should have gotten the following error message from the Java compiler:


    HelloWindow.java:6: cannot resolve symbol
    symbol  : method printInWindow (java.lang.String)    
    location: class HelloWindow
        printInWindow("Hello World!");
        ^
    1 error
    
Figure 18.3

What all of this means is that the compiler doesn't know about the method named printInWindow( ); it is not part of your program and it is not part of Java.  As I mentioned above, it is in the class I've written named ExtendsStuff.

Here's the source code for ExtendsStuff.

Copy and Paste the contents into a file named "ExtendsStuff.java" and compile it.  I pasted into Notepad to make sure it can be done.

Take a look at it.  Just as it extends class Frame, your HelloWindow class needs to be an extension of ExtendsStuff.  When you extend ExtendsStuff, you'll have access to all of the methods in it (and the class(es) it extended) provide.  Once your program extends ExtendsStuff, it will have access to printInWindow( ).

So, change the first line of your source code to look like this.


    class HelloWindow extends ExtendsStuff    
    
Figure 18.4

This gets you one step closer.  However, it still won't compile.  If you tried, you got the error

  
      HelloWindow.java:6: non-static method printInWindow(java.lang.String)    
                          cannot be referenced from a static context
          printInWindow("Hello World!");
          ^
      1 error
    
Figure 18.5

What's this "cannot be referenced from a static context"???

The problem is that we need to create an object that contains the method printInWindow( ).  As I mentioned in the "What's a Class?" lesson, main( ) is special.  Notice that one of the keywords in its declaration is "static" and it's this modifier that, although necessary, is causing our problem.


Instantiation - Turning a class into an object

If you look closely at Example 16.1 you'll notice that we invoke the method println( ) with some stuff in front of it.  "System.out." is prefixed to "println( )".  Think of this prefix as a reference (a pointer) to an object that is part of all Java implementations.  System.out is a field containing a reference to an object (a PrintStream object) in it.  This field has been initialized to direct println( )'s output (the argument we provide) to the console - the window where the JVM was started.  This is the window where you typed in the "java" command.

Since printInWindow( ) is a method defined in class ExtendsStuff, you need to create an object for the JVM that contains it.

instantiation - to represent (an abstraction) by a concrete instance.   [Webster's New Collegiate Dictionary]

Creating an object based on some class is called instantiation

You are creating a real instance of the class.  The class is just source code.  You should think of your source code as a recipe.  When you want to make something from a recipe, you first gather everything you need to do it.  You gather the ingredients, appliances you need, the chef, and her helpers.  This is what the new operator does.  It gets you a pointer to an object created for the expression to the right of the new operator.  The Java Virtual Machine (JVM) needs this object to do anything.

So, what does the syntax of Java source code look like to do what we need?

It's a variable declaration with an initializer.  We store a pointer to the created object (a new instance of the class) in a variable.  I'm not ready to talk about Java's variables yet; so, for now, just memorize the statement:


    classname identifier = new classname( );    
  
Figure 18.6

By substituting "HelloWindow" for classname and by giving the variable (the thing we store the returned pointer in) the name "obj" we end up with:


    HelloWindow obj = new HelloWindow( );    
    
Figure 18.7

Notice that this is two steps:

  1. creating the object, and
  2. storing a pointer to it in something you give a name (identifier) to.

I want to point out something to make sure you caught it, and understand it, before we move on.  Notice that although printInWindow( ) is in ExtendsStuff, I've created a HelloWindow object.  Remember that HellowWindow inherits ExtendsStuff's methods, so a HelloWindow object is also an ExtendsStuff object.  It is better to create a HelloWindow object in main in the HelloWorld class.  We will need it once we have methods in our main class that we want to invoke.


Invocation - Executing a Method

Now that you have a object that contains printInWindow( ), you can use the object to invoke it.  The syntax to invoke a method given an object is:
  1. the identifier of the variable containing a reference to the object, followed by
  2. the "dot" operator, followed by
  3. the method's identifier, followed by
  4. arguments expected by the method.

In our case this looks like:


    obj.printInWindow( "Hello World!" );    
    
Figure 18.8

OK... You should now have another working Java program.  Here's the full source code for it.  Read it as a review of what I've just covered.  Then modify your source code to match, compile it, and run it...


    class HelloWindow extends ExtendsStuff
    {

        public static void main (String[] args);    
        {
            HelloWindow obj = new HelloWindow( );
            obj.printInWindow("Hello World!")
        }

    } //end class HelloWindow
    
Example 18.1


Learning About What's Available and How to Use It

Good programmers got that way by reading and experimenting.  What do you read?  To get good, you need to read Java source code that was written by good Java programmers.  This gives you examples of how you do things in Java.  Of course you are going to run into things that you don't know.  In these cases, you need to look up the things you've never used in documentation and read about them. 

I followed the standards for creating Java class and method documentation when I wrote ExtendsStuff.  Here is Java documentation for ExtendsStuff.

Check out the documentation.  The first thing that is presented is the class hierarchy:

java.lang.Object
 |
 +--java.awt.Component
     |
     +--java.awt.Container
         |
         +--java.awt.Window
             |
             +--java.awt.Frame
                 |
                 +--ExtendsStuff

As I mentioned, I extended the class Frame.  But, I didn't mention that Frame extended a class called Window, and that Window extended a class called Container, etc...

You can skip past much of the documentation for now, but I want to point out three other sections that you can get valuable information from:

  1. the class description (overview),
  2. the Method Summary section, and
  3. the Method Detail section.
The class description is the part that starts off just like your Java source code, i.e., it contains the "class header" - the word class, the name of the class (its identifier), and the extends stuff, etc....  Following the class header is a paragraph or more which describes what the class does.  You can use this to decide whether or not it does what you need.  Here is the class description for ExtendsStuff:
    public class ExtendsStuff
    extends java.awt.Frame

    This class is used to introduce the concept of inheritance,
    and building on top of the existing things that are sort-of
    what you want to do.  In the lesson "What's Java?," the
    Edit-Compile-Execute process was introduced with a simple
    application that used System.out.println( ) to display a
    String.  This class provides a mechanism to display a String
    in a pop-up window by invoking the method: printInWindow( ).
The Method Summary section appears in the form of a table with a couple of lines for each method that the class contains that are available to you.  It gives you the basic information you need to figure out how to invoke it in your Java source code.  Each method name is an HTML link to the detailed description of the method in the following section.

The Method Details section contains full descriptions of what the methods do.  Here you will find multiple paragraphs about each method that the class provides.  The descriptions include more information about the arguments that the method expects.  And, it contains HTML links to any related functionality that you may want to check out.


Summary

You now know one of the most powerful features of Java - inheritance.   You have extended a class and with a couple of lines of Java source code, you've created a pop-up window and displayed a message in it.  To do this, you used the "extends" keyword in your class header along with the name of the class that you wanted to use as the basis for your class.  To gain access to the functionality in this class that you wanted, you had to create an instance of the class - an object.  Finally, you used the "." (also known as the dot ) operator to invoke a method of the class from the object instance of the class.

For you to continue on, writing more Java programs that take advantage of existing functionality available to you, you need to do research.  You will want to read examples of Java programs to see what the source code looks like that does things you are interested in doing yourself.  You will want to read the standardized Java documentation available on-line to build a deeper understanding of what's available.  It might be a bit confusing for now, but you'll see patterns as time goes on.


Back to Table of Contents
Back to previous Lesson ( What's a Class? )
On to next Lesson ( Types )