The JavaTM Tutorial

| Start of Tutorial > Start of Trail > Start of Lesson | Search Feedback Form

Trail: Learning the Java Language
Lesson: Object-Oriented Programming Concepts

## How Do These Concepts Translate into Code?

> Now that you have a conceptual understanding of object-oriented programming let's look at how these concepts get translated into code.

> Here is an applet named `ClickMe`. A red spot appears when you click the mouse within the applet's bounds.

> > Note: The above applet requires JDK 1.1. If you are using an older browser that does not support 1.1, you won't be able to run the applet. Instead, you need to view this page in a 1.1 browser, such as HotJava, the JDK Applet Viewer (`appletviewer`), or certain versions of Netscape Navigator and Internet Explorer. For more information about running applets, refer to About Our Examples.

> The `ClickMe` applet is a relatively simple program and the code for it is short. However, if you don't have much experience with programming, you might find the code daunting. We don't expect you to understand everything in this program right away, and this section won't explain every detail. The intent is to expose you to some source code and to associate it with the concepts and terminology you just learned. You will learn the details in later trails.

### The Source Code and the Applet Tag for ClickMe

> To compile this applet you need two source files: `ClickMe.java` and `Spot.java`. To run the applet you need to create an html file with this applet tag in it:

> >     <applet code="ClickMe.class"
> >             width="300" height="150">
> >     </applet>

> Then load the page into your browser or the appletviewer tool. Make sure all the necessary files are in the same directory.

> Note: If you're having problems running this example:
> - Make sure you download both `Spot.java` and `ClickMe.java` and place them in the same directory.
> - If you can compile one file but not the other, you probably have a CLASSPATH problem. If "`.`" (indicating your current directory) isn't in your class path, the `ClickMe` class can't find the `Spot` class, even though they are in the same directory. Try unsetting CLASSPATH and recompiling, like this:

>   >     set CLASSPATH=
>   >     javac ClickMe.java

>   If your problem is fixed, then you should modify your global CLASSPATH variable to add "`.`" to it. See Update the PATH variable (for Win32) (or the appropriate documentation for your platform).

### Objects in the ClickMe Applet

> Many objects play a part in this applet. The two most obvious ones are the ones you can see: the applet itself and the spot, which is red on-screen.

> The browser creates the applet object when it encounters the applet tag in the HTML code containing the applet. The applet tag provides the name of the class from which to create the applet object. In this case, the class name is `ClickMe`..

> The `ClickMe`.applet in turn creates an object to represent the spot on the screen. Every time you click the mouse in the applet, the applet moves the spot by changing the object's `x` and `y` location and repainting itself. The spot does not draw itself; the applet draws the spot, based on information contained within the spot object.

> Besides these two obvious objects, other, nonvisible objects play a part in this applet. Three objects represent the three colors used in the applet (black, white, and red); an event object represents the user action of clicking the mouse, and so on.

### Classes in the ClickMe Applet

> Because the object that represents the spot on the screen is very simple, let's look at its class, named `Spot`. It declares three instance variables: `size` contains the spot's radius, `x` contains the spot's current horizontal location, and `y` contains the spot's current vertical location:

> >     public class Spot {
> >         //instance variables
> >         public int size;
> >         public int x, y;

> >         //constructor
> >         public Spot(int intSize) {
> >             size = intSize;
> >             x = -1;
> >             y = -1;
> >         }
> >     }

> Additionally, the class has a constructor-- a subroutine used to initialize new objects created from the class. You can recognize a constructor because it has the same name as the class. The constructor initializes all three of the object's variables. The initial value of `size` is provided as an argument to the constructor by the caller. The `x` and `y` variables are set to -1 indicating that the spot is not on-screen when the applet starts up.

> The applet creates a new spot object when the applet is initialized. Here's the relevant code from the applet class:

> >     private Spot spot = null;
> >     private static final int RADIUS = 7;
> >     ...
> >     spot = new Spot(RADIUS);

> The first line shown declares a variable named `spot` whose data type is `Spot`, the class from which the object is created, and initializes the variable to `null`. The second line declares an integer variable named `RADIUS` whose value is `7`. Finally, the last line shown creates the object; `new` allocates memory space for the object. `Spot(RADIUS)` calls the constructor you saw previously and passes in the value of `RADIUS`. Thus the spot object's `size` is set to 7

> The figure on the left is a representation of the `Spot` class. The figure on the right is a spot object.

### Messages in the ClickMe Applet

> As you know, object A can use a message to request that object B do something, and a message has three components:
> 1. The object to which the message is addressed
> 2. The name of the method to perform
> 3. Any parameters the method needs
> Here are two lines of code from the `ClickMe` applet:

> >     g.setColor(Color.white);
> >     g.fillRect(0, 0, getSize().width - 1, getSize().height - 1);

> Both are messages from the applet to an object named `g`--a `Graphics` object that knows how to draw simple on-screen shapes and text. This object is provided to the applet when the browser instructs the applet to draw itself. The first line sets the color to white; the second fills a rectangle the size of the applet, thus painting the extent of the applet's area white.

> The following figure highlights each message component in the first message:

### Inheritance in the ClickMe Applet

> To run in a browser, an object must be an applet. This means that the object must be an instance of a class that derives from the `Applet` class provided by the Java platform.

> The `ClickMe` applet object is an instance of the `ClickMe` class, which is declared like this:

> >     public class ClickMe extends Applet implements MouseListener {
> >        ...
> >     }

> The `extends Applet` clause makes `ClickMe` a subclass of `Applet`. `ClickMe` inherits a lot of capability from its superclass, including the ability to be initialized, started, and stopped by the browser, to draw within an area on a browser page, and to register to receive mouse events. Along with these benefits, the `ClickMe` class has certain obligations: its painting code must be in a method called `paint`, its initialization code must be in a method called `init`, and so on.

> >     public void init() {
> >         ... // ClickMe's initialization code here
> >     }

> >     public void paint(Graphics g) {
> >         ... // ClickMe's painting code here
> >     }

### Interfaces in the ClickMe Applet

> The `ClickMe` applet responds to mouse clicks by displaying a red spot at the click location. If an object wants to be notified of mouse clicks, the Java platform event system requires that the object implement the `MouseListener` interface. The object must also register as a mouse listener.

> The `MouseListener` interface declares five different methods each of which is called for a different kind of mouse event: when the mouse is clicked, when the mouse moves outside of the applet, and so on. Even though the applet is interested only in mouse clicks it must implement all five methods. The methods for the events that it isn't interested in are empty.

> The complete code for the `ClickMe` applet is shown below. The code that participates in mouse event handling is red:

> >     import java.applet.Applet;
> >     import java.awt.*;
> >     import java.awt.event.*;

> >     public class ClickMe extends Applet implements MouseListener {
> >         private Spot spot = null;
> >         private static final int RADIUS = 7;

> >         public void init() {
> >             addMouseListener(this);
> >         }

> >         public void paint(Graphics g) {
> >             // draw a black border and a white background
> >             g.setColor(Color.white);
> >             g.fillRect(0, 0, getSize().width - 1, getSize().height - 1);
> >             g.setColor(Color.black);
> >             g.drawRect(0, 0, getSize().width - 1, getSize().height - 1);

> >             // draw the spot
> >             g.setColor(Color.red);
> >             if (spot != null) {
> >                 g.fillOval(spot.x - RADIUS,
> >                            spot.y - RADIUS,
> >                            RADIUS * 2, RADIUS * 2);
> >             }
> >         }
> >         public void mousePressed(MouseEvent event) {
> >             if (spot == null) {
> >                 spot = new Spot(RADIUS);
> >             }
> >             spot.x = event.getX();
> >             spot.y = event.getY();
> >             repaint();
> >         }
> >         public void mouseClicked(MouseEvent event) {}
> >         public void mouseReleased(MouseEvent event) {}
> >         public void mouseEntered(MouseEvent event) {}
> >         public void mouseExited(MouseEvent event) {}
> >     }

### API Documentation

The `ClickMe` applet inherits a lot of capability from its superclass. To learn more about how `ClickMe` works, you need to learn about its superclass, `Applet`. How do you find that information? You can find detailed descriptions of every class in the API documentation, which constitute the specification for the classes that make up the Java platform.

The API documentation for the Java 2 Platform is online at `java.sun.com`. It's helpful to have the API documentation for all releases you use bookmarked in your browser.

- API documents for Java 2 Platform, Standard Edition, v1.3
- API documents for Java 2 Platform, Standard Edition, v1.2
- API documents for JDK 1.1
- API documents for JDK 1.0.2

To learn more about all the classes and interfaces from the Java platform used by the ClickMe applet, you can look at the API documentation for these classes:

- `java.applet.Applet`
- `java.awt.Graphics`
- `java.awt.Color`
- `java.awt.event.MouseListener`
- `java.awt.event.MouseEvent`

### Summary

> This discussion glossed over many details and left some things unexplained, but you should have some understanding now of what object-oriented concepts look like in code. You should now have a general understanding of the following:
> - That a class is a prototype for objects
> - That objects are created from classes
> - That an object's class is its type
> - How to create an object from a class
> - What constructors are
> - How to initialize objects
> - What the code for a class looks like
> - What class variables and methods are
> - What instance variables and methods are
> - How to find out what a class's superclass is
> - That an interface is a protocol of behavior
> - What it means to implement an interface

| Start of Tutorial > Start of Trail > Start of Lesson | Search Feedback Form

Copyright 1995-2001 Sun Microsystems, Inc. All rights reserved.