Next Previous Up Top

4 Class Relationships

4.10 A Small Example of Using Inheritance

4.10 A Small Example of Using Inheritance

As an example of the use of inheritance and interfaces, consider Java applets (introduced in Section 1.6, Page 8). An applet is designed to be part of a WWW page, is downloaded from a server and is implemented using Java objects. In order to integrate correctly into a WWW page, the Java class library provides a class Applet which implements the core infrastructure needed by applet objects (allowing them to interact and be displayed by a WWW browser). The WWW browser's Java environment, in turn, provides a framework into which applet objects can fit.

Creating a new applet is done by declaring a new class as an extension of the basic Applet class. The following is a basic skeleton of such a subclass:

class MyApplet extends Applet
	// Applets usually need to be initialized.
	public void init() { ... }

	// If an applet uses resources it may have to override:
	public void destroy() { ... }

	// A redrawing function may or may not be required.
	public void paint(Graphics g) { ... }

	// A function for dealing with user interaction may
	// or may not be required.
	public void action(Event e, Object o) { ... }

	// Sophisticated applets may override:
	public void start() { ... }
	public void stop() { ... }

Class Applet provides a collection of methods which can be overridden by a subclass to specialize its behaviour for whatever the new applet needs to do; if the subclass chooses not to declare an overriding of a method then the 'default' method supplied by Applet will be used. As the subclass inherits the interface needed by applet objects, its instance objects can function fully as applets. Dynamic binding takes care of correctly calling the methods of the new applet.

Copyright 1997 Russel Winder and Graham Roberts

Last updated: 6 Oct 1997