- Commanding a Turtle
- Adding New Commands
- Iteration & Animation
- Hierarchical Structure
- Procedure Inputs
- Operators & Expressions
- Defining Operators
- Words & Sentences
- User Interface Events
- What If? (Predicates)
- Local Variables
- Global Variables
- Word/Sentence Iteration
- Mastermind Project
- Turtles As Actors
- File Input/Output
- A Java Program
- What's a Class?
- Extending Existing Classes
- Turtle Graphics
- Control Flow
- User Interface Events
- What Is TG?
- TG Directives
- jLogo Primitives
- TG Editor
- Java Tables
- Example Programs
- *** New ***:
- December 13, 2008
- January 6, 2012
- March 15, 2013
- January 20, 2014
- February 13, 2014
- July 29, 2014
- January 18, 2016
- January 29, 2016
- August 19, 2016
Extending Existing Classes - Inheritance
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 drone. A quick look at one shows we're going to need to create some plastic things, the propellers, a body. The frame to hold everything together will need to be light-weight metal. There will be motors, a battery for power. There will be attachments like sensors, a camera. Look inside and you will see we need a circuit board with 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, don't usually grow their own vegetables. A carpenter doesn't chop down trees to make lumber and forge his own steel 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 your drone, you would outsource much of the stuff you need to do. What you have is an idea about how to make your drone unique, attractive to customers; your creativity is your added value. You would let electronic manufacturers, world-wide, submit proposals to you, to build the actual devices for you. And, since you are going to use Java, you will not need to start your programming effort on low-level basics stuff.
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. There are a few operating systems available in open-source form, Linux is one. Since Java is available on Linux, you can use it. There are a couple of Java-based drone software platforms available. Here is a link to the YADrone Java class hierarchy. And you can take advantage of Java's rich libraries of existing classes. How many are there? This question was asked at stackoverflow.com and the answer is a lot:
|Number of Classes|
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 we used to write on when using an overhead projector (before notebook computers and presentation software became the standard). 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.
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 jLogo. You learned how to handle both mouseClicked Events and keyPressed Events. But, handling events in Java is a little more work than in jLogo, 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 added to the Frame. So, I'm going to do this for you too.
I've created a class named ExtendsStuff that extends Frame and does all the stuff you haven't learned about yet. It inherits all of the stuff that a Frame can do plus contains a method named printInWindow( ). By extending it, you will inherit everything it can do. printInWindow( ) can be used much like the way you used System.out.println( ) in Hello.java.
Here is the source code for ExtendsStuff.java. Copy it and Paste the contents into an editor on your system, check it out, save it to a file named ExtendsStuff.java and compile it to generate a .class file.
So, how do we use ExtendsStuff.java, its printInWindow( ) method to get a window to popup with some text in it?
Can we use Hello.java as a model? If so, what changes need to be made to the Hello.java source code? Before I show you the needed changes, take a few minutes and take a shot at it. Write a class named HelloWindow that extends ExtendsStuff.java to display some text in a window by using its printInWindow( ) method.
Go back and review the template for a Java class (Figure 21.3) if you are having problems. In the body of main( ), invoke printInWindow( ) instead of System.out.println( ). Compile your program, run it. 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 named HelloWindow.java that contains something that looks like Figure 22.2.
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, the error message you should have gotten from the Java compiler is shown in Figure 22.3.
What all of this means is that the Java compiler doesn't know about the method named printInWindow( ); it is not part of your program and it is not part of Java. It is in the class I've given you, ExtendsStuff. So, how does your program indicate to the Java compiler that it needs to find printInWindow( ) in ExtendsStuff?
I've given you clues. Remember... this lesson is all about extending existing classes. And, I've given you ExtendsStuff.java for you not only to use, but to read and learn from as well.
Take a look at it. Just as it extends class Frame, your HelloWindow class needs to extend ExtendsStuff. When you extend it, you'll inherit all of the methods in it (and in the class it extended). Once your program extends ExtendsStuff, it will have access to printInWindow( ).
So, change the first line of your source code to look like Figure 22.4.
This gets you one step closer. However, it still won't compile. Try it and see what happens. You should get an error that looks like Figure 22.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 at the root of our problem.
Instantiation - Turning a class into an object
Take another look at Hello.java and reread the line containing the text println( ). Checkout the stuff that comes before 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 (a variable) which contains a reference to an object (a PrintStream object) in it. This field is initialized when the Java Virtual Machine starts up. Think of a PrintStream as a little person that takes stuff and writes it out somewhere. The somewhere is setup when the PrintStream is created. When you typed in the "java" command, the JVM started up and created a PrintStream object that was associated with where you were typing. On a computer running Windows, this is usually a CommandPrompt window.
println( ) is a method provided by PrintStream.
Since printInWindow( ) is a method defined in class ExtendsStuff, we need to create an ExtendsStuff object. We can then use this object to reference printInWindow( ).
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 (concrete) instance of a class. The source code representation of a class is just an abstraction. It's an idea. 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 thing following the new operator. The Java Virtual Machine (JVM) needs this object to perform methods that are in the class the object represents.
So, what does the syntax of Java source code look like to do what we need?
It's a variable declaration with an initializer. This is very similar to localmake in Logo. We store a pointer to an object created (a new instance of representing the class) in a variable. I'm not ready to talk about Java's variables yet; so, for now, just memorize the statement in Figure 22.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 Figure 22.7.
Notice that this is two steps:
- creating the object, and
- storing a pointer to it in something you give a name (identifier) to.
I want to point out something just 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 our classes contain methods that we want to invoke.
Invoking a Method
Now that you have an object that contains printInWindow( ), you can use the object to invoke it. The syntax to invoke a method, given an object, is:
- the identifier of the variable containing a reference to the object, followed by
- the "dot" operator, followed by
- the method's identifier, followed by
- arguments expected by the method, and
- finished off with a semicolon.
In our case this looks like Figure 22.8.
OK... You should now have another working Java program. Figure 22.9 shows the full source code for it. Read it as a review of what I've just covered. If your source code doesn't match it, make the necessary changes and then compile it, and run it...
You should see a window pop up. Figure 22.10 shows the window that appeared on my computer.
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 source code that was written by good programmers. This gives you examples of how you do things. Of course you are going to run into stuff 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:
- the class description (overview),
- the Method Summary section, and
- 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.
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.
Go to the Table of Contents
On to Types