The JavaTM Tutorial

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

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 applet shown above 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 associate it with the concepts and terminology you just learned. You will learn about the details in subsequent trails and lessons.

### Objects in the ClickMe Applet

> Many objects play a part in this applet. The two most obvious ones are the ones that you can see: the applet itself and the spot.

> The browser creates the applet object when it encounters the applet tag in the HTML code for this page. 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 it based on information contained within the spot object.

### Classes in the ClickMe Applet

> Because the object that represents the spot on the screen is very simple, let's look at that class. Following is the code for the class named `Spot`. It declares three member 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 {
> >         public int size;
> >         public int x, y;

> >         public Spot(int size) {
> >             this.size = size;
> >             this.x = -1;
> >             this.y = -1;
> >         }
> >     }

> Additionally, the class has a constructor--a function used to initialize new objects created from the class. You can recognize a constructor in a class 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 by the caller. The `x` and `y` variables get set to -1 indicating that the spot is not onscreen 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` and initializes the variable to null. The second line declares a 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.

### Messages in the ClickMe Applet

> As you know, object A can use a message to request that object B do something and that there are three components to a message:
> 1. The object to whom the message is addressed
> 2. The name of the method to perform
> 3. Any parameters needed by the method
> 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 shapes and text on screen. This object is provided to the applet when it needs to draw itself by the drawing mechanism implemented by the Java platform. 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 to 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() {
> >         ...
> >     }

> >     public void paint(Graphics g) {
> >         ...
> >     }

### 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 with the Java platform 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) {}
> >     }

### Summary

> This section 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. After reading this section, you should have a general understanding or a feeling for the following:
> - 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
> - What the code for a class looks like
> - What member variables are
> - How to initialize objects
> - How to find out what a class's superclass is
> - What it means to implement an interface

### API Links

> The `ClickMe` applet inherits a lot of capability from its superclass. To figure out more about the class, you must know about its superclass, `Applet`. How do you find that information? You can find descriptions of every class and every method implemented by every class in the API documents, which are also known as "javadocs". The set of javadocs constitutes the API specification for the classes that make up the Java platform. When appropriate, The Java Tutorial contains inline links to classes in the javadocs. For example, this sentence contains a link to the 1.2 javadocs for the `Applet` class.

> The javadocs come with the JDK download or you can view them at java.sun.com. You should consider bookmarking these links:

> - Javadocs for Java 2 Platform, Standard Edition, v1.2
> - Javadocs for JDK 1.1
> - Javadocs for JDK 1.0.2

> Use the following links to learn more about the classes and interfaces from the Java platform used by the `ClickMe` applet:

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

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