Session 8 Lecture Notes for First Course in Java
course homepage      course calendar

05 May 2003

This lecture covers the reading in Chapter 8: Inheritance and the applet section of Chapter 12.

Inheritance from the superclass

The keyword super

Multilevel hierarchy

Constructors: priority of the ancestors

Using super to overcome method overriding

Dynamic Method Dispatch

Abstract Classes

final with Inheritance

The Object Class


Applets


Quiz

Homework Assignment


Inheritance from the superclass

A subclass inherits from its superclass.

The keyword super

Let us look at two uses for the keyword super.

calling the constructor of the superclass

If you call super() at the beginning of a subclass constructor, you are actually calling the constructor of the superclass.
This example user super() to gain access to superclass members, and it also adds its own member, weight.

accessing superclass members

The keyword super also gives you access to properties and methods of the superclass.

Multilevel hierarchy

A superclass can have multiple subclasses. Each subclass can only have one superclass. This is called single inheritance and is one of the differences between Java and C++. Each subclass, in turn, can have multiple subclasses.

Constructors: priority of the ancestors

In many cultures, when it comes to offering food, the ancestors (or the gods) have priority over living people, and the elders have priority over the younger people.
Java is like that too because the constructor of the superclass has priority over the constructor of the subclass.
This observance of the hierarchy ensures that inheritance occurs before any subsequence local specialization.

The output is:

constructing C2
Inside A's constructor.
Inside B's constructor.
Inside C2's constructor.
constructing D
Inside A's constructor.
Inside B's constructor.
Inside C's constructor.
Inside D's constructor.

Note that execution follows the class hierarchy even though the compiler had to parse a source file that put a subclass of a subclass before the highest superclass.

Using super to overcome method overriding

Just as a local variable in an inner code block hides a variable of the same name in an outer code block (see session2.htm#codeblocks), so a local method overrides and hides a method of the same name in a superclass.

The output is:

k: 3

Automatic method overriding is a useful default to overcome what some programmers call a "namespace collision". However, what if you want to use the superclass implementation of a method with the same name as the current class method? The answer is use the keyword super because it gives you access to all the members of the superclass, including properties and methods.

The output is:

This subclass has a show method that calls the superclass show method.
only the subclass sees k: 3
superclass show: i and j: 1 2

Dynamic Method Dispatch

Dynamic method dispatch supports runtime polymorphism by allowing subclasses to override methods while also allowing the superclass to define a general form for the overridden methods..

Suppose you have one server machine in Washington and three client machines, one in Japan, one in California, and one in Morocco.
Each local area wants to have its own way of implementing certain logic, but the central office does want to impose some kind of standard.
One solution would be to have a superclass that specifies a named method, but allow the localities to call their local version.
In this case, we have inheritance from a superclass along with polymorphism of the method.
What determines which form of the polymorphism to execute? A runtime event: the assignment of a subclass reference to the superclass reference. In effect, the superclass acts as if it knows the subclass implementation, even though it cannot. We say that the subclass method overrides the superclass method by virtue of dynamic (runtime) dispatch (calling a reference of the superclass that holds the object of a subclass).

The output is:

Inside A's callme method
Inside B's callme method
Inside C's callme method

For a less trivial example, consider shapes that derive from a general (almost abstract) shape.

The output is:

Inside Area for Rectangle.
Rectangle area is 45.0
Inside Area for Triangle.
Triangle area is 40.0
Area for Figure is undefined.
General figure area is 0.0

Abstract Classes

We said that the previous example defined a general shape that was "almost" abstract.
In the previous example, we had an area method for the superclass, but it could not have any definition that was common to both its subclasses.
Perhaps there is a more elegant way to deal with truly abstract methods without pretending they are more definite than they actually are, and without having to override something that, in a sense, doesn't belong there anyway.
Well, Java supports the concept of an abstract class with the keyword abstract.
An abstract class cannot general objects (instances). Instead, it is the responsibility of the subclass(es) to instantiate the abstract class.

The output is:

Subclass B implements callmeInAbstract.
Abstract superclass A has a concrete method.

Now that we understand the syntax, let us re-implement the area calculation from an general superclass. This time, the area method of the superclass can be appropriately abstract.

The output is:

Inside Area for Rectangle.
Area is 45.0
Inside Area for Triangle.
Area is 40.0

[another take on Abstract Classes and Methods]

http://java.sun.com/docs/books/tutorial/java/javaOO/abstract.html

Sometimes, a class that you define represents an abstract concept and, as such, should not be instantiated. Take, for example, food in the real world. Have you ever seen an instance of food? No. What you see instead are instances of carrot, apple, and (our favorite) chocolate. Food represents the abstract concept of things that we all can eat. It doesn't make sense for an instance of food to exist.

Similarly in object-oriented programming, you might want to model an abstract concept without being able to create an instance of it. For example, the Number class in the java.lang package represents the abstract concept of numbers. It makes sense to model numbers in a program, but it doesn't make sense to create a generic number object. Instead, the Number class makes sense only as a superclass to classes like Integer and Float, both of which implement specific kinds of numbers.

Another example might be library materials, such as books, magazines, CDs, and videos. You might have an abstract class, LibraryItem, and make specific types of library items be subclasses of LibraryItem. However, you might not have any use for a LibraryItem object, because any physical library item is either a book, magazine, CD, or video, and you want to handle it appropriately. What would be the purpose of the abstract LibraryItem class? To specify the attributes and behavior that are common to all library items. Books, magazines, CDs, and videos might all have attributes such as title, card_catalog_number, replacement_price and isCheckedOut. These library items might all have behavior such as checkOut(), checkIn(), searchIfLost(), repair(), and replace().

A class such as Number, which represents an abstract concept and should not be instantiated, is called an abstract class. An abstract class is a class that can only be subclassed-- it cannot be instantiated.

To declare that your class is an abstract class, use the keyword abstract before the class keyword in your class declaration:

abstract class Number {
    . . .
}

If you attempt to instantiate an abstract class, the compiler displays an error similar to the following and refuses to compile your program:

AbstractTest.java:6: class AbstractTest is an abstract class.
It can't be instantiated.
        new AbstractTest();
        ^
1 error

Abstract Methods

An abstract class can contain abstract methods, that is, methods with no implementation. In this way, an abstract class can define a complete programming interface, thereby providing its subclasses with the method declarations for all of the methods necessary to implement that programming interface. However, the abstract class can leave some or all of the implementation details of those methods up to its subclasses.

Let's look at an example of when you might want to create an abstract class with an abstract method in it. In an object-oriented drawing application, you can draw circles, rectangles, lines, Bezier curves, and so on.

Each of these graphic objects share certain

You can take advantage of these similarities and declare them all to inherit from the same parent object--GraphicObject.

 

However, the graphic objects are also substantially different in many ways: drawing a circle is quite different from drawing a rectangle. The graphics objects cannot share these types of states or behavior. On the other hand, all GraphicObjects must know how to draw themselves; they differ merely in how they are drawn. Objects of the subclasses have specialized implementation. This is a perfect situation for an abstract superclass.

First you declare an abstract class, GraphicObject, to provide member variables and methods that are shared by all subclasses, such as the current position and the moveTo() method. GraphicObject also declares abstract methods for methods, such as draw(), that need to be implemented by all subclasses, but are implemented in entirely different ways (no default implementation in the superclass makes sense). The GraphicObject class would look something like this:

abstract class GraphicObject {
    int x, y;
    . . .
    void moveTo(int newX, int newY) {
        . . .
    }
    abstract void draw();
}

Each non-abstract subclass of GraphicObject, such as Circle and Rectangle, would have to provide an implementation for the draw() method.

class Circle extends GraphicObject {
    void draw() {
        . . .
    }
}
class Rectangle extends GraphicObject {
    void draw() {
        . . .
    }
}

An abstract class is not required to have an abstract method in it. However, any class that has an abstract method in it or that does not provide an implementation for any abstract methods declared in its superclasses must be declared as an abstract class.

final with Inheritance

The keyword final means all of the following:

The Object Class

Because all objects inherit from the class Object, all objects have access to certain method.
Among these methods are the following:


Introduction to Applets

Example: animated blobs at http://www.mandrixx.net/javasimple.html

Sun's web site for applets: http://java.sun.com/applets/

Sun's tutorial on writing applets: http://java.sun.com/docs/books/tutorial/applet/overview/index.html
and includes a dog barking! http://java.sun.com/docs/books/tutorial/applet/appletsonly/sound.html

What is an applet?

Unlike a Java application, a Java applet runs inside of a browser, such as Netscape Navigator or Internet Explorer.

Your SDK provides a directory will demonstration applets. The path might be something similar to the following.
D:\java\j2sdk1.4.1_01\demo\applets

Applet Viewer

You can also run an applet by using the applet viewer the comes with the JDK. The applet view also allows you to debug your applet.

The appletview resides in the bin directory of your JDK. You can launch an applet by giving the relative path to the HTML page for the applet. For example:

D:\java\j2sdk1.4.1_01\bin>appletviewer ..\demo\applets\Fractal\example1.html
which lauches the AppletViewer and runs a dynamic example:

Here is another example:

D:\java\j2sdk1.4.1_01\bin>
appletviewer ..\..\teachjava\spring2003\session8\SimpleApplet.java

How does an applet run?

The differences between an applet and an application are that an applet:

D:\java\j2sdk1.4.1_01\bin>
appletviewer ..\..\teachjava\spring2003\session8\AppletSkel.java

The "sandbox" is a security layer around the applet that prevents the applet from accessing the following:

(These restrictions can be customized by the client through the browser or by modifying the security properties file.)

Example with some motion.

D:\java\j2sdk1.4.1_01\bin>
appletviewer ..\..\teachjava\spring2003\session8\AppletSkel.java

We can also run the applet in an HTML page:

<html>
<head>
<title>an applet</title>
</head>
<body>
<applet width="800" height="400" code="SimpleBanner.class"
</applet>
</body>
</html>

D:\java\teachjava\spring2003\session8\SimpleBanner.html

Signed Applets

Signed applets are applets that are certified to come from a registered (and therefore hopefully trustworthy) source.

The provider of an applet can get the applet out of the "sandbox" restrictions by signing the applet.

If the user's browser detects a signed applet, it displays the certificate and prompts the user to respond by trusting this applet, all applets from this applet provider, or declining to trust this applet.

To sign your applet, you work with a third party, such as VeriSign, http://www.verisign.com/products/signing/index.html
that provides a digital signature, or key, that authenticates you as the provider of the applet and guarantees that the applet code has not been alerted. 

The client actually communicates both with the applet provider and the third party.

A signed applet has none of the applet restrictions, and is essentially an application even though it runs in the browser.

Basic HTML to embed an applet in a web page

To embed an applet in a web page, you must write HTML code to reference the the applet's class file and the size of the applet.

Sun describes this at http://java.sun.com/products/jdk/1.1/docs/guide/misc/applet.html

<applet code="MyApplet.class" width=100 height=140></applet>

Minimal HTML to display an applet

The glossary applet at http://www.wordesign.com/java/glossary/ uses very little HTML to display a glossary of Java terms:

<html>
<head>
<title>Glossary of Java Terms (by Thomas Albert and Alex Aybes)</title>
</head>
<body>
Glossary of Java Terms (click on a term for the definition)<br>
<APPLET CODE="com.wordesign.glossary.GlossaryApplet.class" height="80%" width="80%"></APPLET>
</body>
</html>

Note: The applet tag requires the fully qualified name of the class, which is the name of the class package followed by the class name.

Creating an applet

To create an applet, you extend the applet class and override methods of the java.applet package.

extending the applet class

Java defines the applet object in the java.applet package.

Key method definitions are:

Swing applets versus AWT applets

The java.awt packages provide the abstract windowing toolkit (AWT), which supports graphical user interfaces (GUIs).

More recent versions of Java also include extensions called javax.swing packages, which add more support for GUIs.

Basic methods: init(), paint()

The init() method is called when the browser is done loading the applet. Using this method, you will typically do all the initializations your applet needs.

An applet inherits the paint() method from the Component class. The paint() method takes as argument an instance of the Graphics class. The graphics object provides methods to draw geometric shapes, text, or other things.

For your first applet, you will typically override the paint() method to do your custom drawing.

Demonstration of an Applet

**********************************

Java Applet Example

import java.awt.Graphics;
import java.awt.Color;
public class HelloApplet extends java.applet.Applet {
	public void paint(Graphics g) {
		g.setColor(Color.red);
		g.drawString("Hello World!", 5, 50);
	}
}

Your HTML page references the applet and defines space to display it:

<HTML>
   <BODY>
      <applet code="HelloApplet.class" width=350 height=130>
      </applet>
   </BODY>
</HTML>

Other aspects

parameters

You can pass parameters to an applet from the HTML code. 
For example, your HTML page might have a parameter, language, with a value, French, that tells the applet to display the French version of the applet.

The syntax to add parameters to your HTML page is:

http://java.sun.com/products/jdk/1.1/docs/guide/misc/applet.html

<applet code="appletname.class" width=400 height=75>
 <param name="language" value="French"> 
 </applet>

How the applet gets parameter values from your HTML page

The applet class provides a method called getParameter() that takes as input a String that represents the name of the parameter. In our example, the parameter would be language. The return value of the getParameter() method is the value of the parameter. In our example, the parameter value is French.

size

The client can resize your applet if you specify the applet size as a percentage of the browser window. Alternatively, you can specify the applet size as a specific number of pixels.


Quiz

  1. What are the three uses for the keyword final?
  2. What is the difference between the keyword super and the keyword this?
  3. What is the difference between method overloading and method overriding?
  4. What is the order in which constructor calls are executed and why is it in this order?
  5. How many superclasses can a subclass have?
  6. What is dynamic method dispatch?
  7. What is an abstract class?
  8. In what way is using an abstract class different from using dynamic method dispatch?
  9. What is Java's Applet Viewer and why would you use it?
  10. Is the entry point of an applet the main() method? Why or why not?

Homework Assignment

Option 1:

Let's look at the source code at
http://www.realapplets.com/tutorial/GuiExample.html

and run the applet:
D:\java\teachjava\spring2003\session8\GuiExample.html

Write a simple applet that works with shapes and GUI widgets.

Option 2:

Research an area of the Java Core APIs and give a 5-10 minute presentation to the class next week. If you would like me to run some code, please email it to me by 8 a.m. Sunday.

______________
course homepage      course calendar