Lesson 2.3 First Applet
Examining Your First Java Applet
In this section, we're going to take a look at your first Java applet. We won't cover the "mechanics" of creating the applet here; that's covered back in Lesson 1.6.
Before you begin this section, you should have installed the Java Development Kit, and know how to editing compile and run a Java program. Here, we'll take a closer look at the program, FirstApplet.java that you entered, compiled, and ran in Lesson 1.6.
Program Organization
As you saw in the previous lesson:
- Every Java program is a class definition.
- A class definition is a blueprint that is used to construct an object; in the case of an applet, you may want to think of that object as a "program object."
Not every Object-Oriented language works like this. In C++, for instance, every program consists of a main() function that may, or may not create different kinds of objects. In Java, there is no separate program entity; there are only classes and object.
The basic structure for every Java program looks like this:
… some stuff
public class SomeClassName
{
… some more stuff
} |
The file name for this program must be SomeClassName.java and the file can contain only one public class definition. (You can define other classes in the same file, but they cannot be public classes.)
Note that this is different than many other programming languages where the program name and the name of the file are not related. In Java, the name of the file and the name of the program must be identical (including case). The file name and the public class it contains must match exactly.
The Class Header
A class definition has two parts: a header and a body. The header "describes" or "declares" the class for the compiler, while the body, [the portion of the class in braces { }], is where the attributes and methods for the class will be defined.
Let's start by examining the header for FirstApplet, and then we'll come back to its body. The FirstApplet class header is written as:
| public class FirstApplet extends Applet |
The first part of this is the declaration public class. This simply tells the compiler:
"Hey! a class definition is coming up!"
so the compiler knows how to interpret the words that follow. Both public and class are two of the fifty-or-so Java keywords. Keywords [also sometimes called reserved words] are the built-in vocabulary of a language. In Java:
- Keywords are always lowercase
- You cannot use keywords as identifiers [the names you supply when you create classes, methods, and attributes]
- You must spell the keywords correctly and use them in the correct context. If you use a keyword inappropriately, or if you misspell it, you will generate a syntax error: a violation of Java's internal rules of grammar.
Name of the Class
When you write the declaration public class, this puts that Java compiler into such a state of anticipation, that it won't be satisfied unless you tell it exactly what class is about to be described. Thus, the next part of the class header must be the class name. Here we've named our class FirstApplet.
While public and class are keywords, FirstApplet is a different kind of beast; FirstApplet is an identifier. An identifier is a word that you make up to name classes, attributes, methods, and variables. You can use any name you like, as long as you follow a few simple rules:
- You can use letters, digits, the currency symbol [$] and the underscore character in your name.
- Your identifier cannot start with a digit.
- You must remember that identifiers are case sensitive . Unlike keywords, you may use uppercase as well as lowercase, but the identifiers cat, Cat, and CAT are not the same!
If you've programmed in another language, such as C, Pascal, or Visual Basic, these rules don't seem too different. [They're not the same, of course. C doesn't allow the $ character, and Pascal identifiers are not case sensitive.]
The biggest difference [when it comes to identifiers] between Java and these other languages is not readily apparent, but pops to the surface when you ask the question, "What's a character?"
Unlike these other languages Java isn't limited to using the ASCII character set [the most widely used computer-character encoding scheme]. Instead, it uses Unicode, the international character set that provides some 65,000 different characters. So, although Java identifiers are limited to characters and digits, those characters and digits can be any valid Unicode character or digit.
Naming Conventions
In programming, as in dining, what is legal is not always appropriate. While it is usually not illegal to eat with your hands, it's often inappropriate, and so most of us obey the social conventions.
Much like social conventions, identifier naming conventions allow you to infer a great deal about an object by the way it is named. Also like social conventions, identifier naming conventions can become prissy and pedantic, ignoring the more important considerations of clarity and simplicity.
It is always more important to make sure that your variable names impart meaning to your audience than that they adhere to some rigid naming rule. To that end, you should follow the "golden rules" that are true in any programming language:
|
Other Recommendations
|
| Before we get to the normal conventions, I should mention two other recommendations. Java allows you to begin a name with an underscore as well as a dollar sign ($), but you should avoid doing so. Java itself uses the dollar sign to create names for "inner classes". To avoid some unusual and hard to find bugs, you should avoid using the dollar sign ($) in your names at all. |
It is also legal to start an identifier with an underscore, but you should avoid that as well. It is just too easy to miss a leading underscore when you are reading code, and if you use them you'll spend many more fruitless hours staring at code that "should" work, but doesn't for some reason.
Beyond that, however, here are the more-or-less agreed upon naming standards in the Java world:
- Class names: CapitalizeEveryWord
- Method and field names: startLowThenCaps
- Constants: CAPS_WITH_UNDERSCORES
What Does extends Applet Mean?
So far, we've taken care of three of the five words in the FirstApplet header; only two to go.
The next word, extends, is a keyword like public and class. The extends keyword means that what precedes it [in this case the public class FirstApplet ], adds something to, or builds upon, what follows it [in this case, something called Applet ].
That makes sense. If a header is supposed to describe a class, this part of the header is describing its lineage. Sort of like:
This is Steve, and his parents are...
The real question is, "What's an Applet, and where does Applet come from?" We can tell right away that Applet isn't a keyword like public or class or extends, because we know that all of the keywords are lowercase, and Applet is capitalized.
Perhaps, our knowledge of convention might help; and, indeed it does. If you look back at the convention for identifiers, you'll see that only classes begin with a capital [like Applet] followed by lowercase characters. In fact, Applet is a class, one of the classes supplied with the JDK.
The Applet class actually has quite a pedigree, which you can discover by looking at its complete name:
java.applet.Applet
Now, if you've been following carefully, you may be a little confused. Was the dot (.) a valid character inside a class name or other identifier? No, it wasn't. Instead, the name, java.applet.Applet describes a class that is contained inside a Java package.
A package describes the place where the specific class we want to use is stored. In this case, the Applet class is in the package, java.applet. [Package names that begin with java are part of the core Java packages, and you are not permitted to modify them.]
If you look back at our class organization at the start of this lesson, you'll see that it starts with the statement:
...some stuff
As you undoubtedly surmised, this was just a placeholder, waiting until the time was right for its explication. The time is right.
What goes in place of "...some stuff" is another Java keyword: import. The import statement tells the javac compiler which packages to look in when it is trying to locate a class.
Specifically, since we told the compiler that FirstApplet extends Applet, we must also tell it where to find the Applet
public class FirstApplet
extends java.applet.Applet |
but that would quickly become tedious. Instead, we can add the following lines to the top of our class file:
import java.applet.*;
import java.awt.*; |
and Java will look first in the java.applet package and then in the java.awt package to locate any classes that we use.
The Class Body
Now that we've taken care of the class header, we're ready to look at the class body, where you’ll define the attributes and methods that make up the class. We'll start by looking at some general style and punctuation issues, and, in the next section, Creating Objects, we'll finish our first class.
In Java, braces {} are used to mark the beginning and end of the class body. Braces are also used to delimit the body of a method, as well as the bodies of loops and selection statements. Just think of braces as markers that say:
{ "this is the beginning of a section"
} "this is the end of a section"
In Java, such a delimited "section" is called a block.
Braces, along with indentation, allow you to quickly see and understand the general struture or "shape" of a program. To facilitate this, every time you use a set of braces, the "stuff" inside the braces should be indented as well.
There are at least two styles of indenting you can use with your braces. Which one you select is a matter of taste. You should be consistent, however. If you use one style in one part of your code, and the other style in another part of your code, it makes your programs harder to read.
Below we'll cover the two most popular styles: Classic Indenting and Vertical-style Indenting.
Classic Indenting
In classic indentation, [also called C-style indentation], the "begin" brace is placed on the same line as the block header, while the "end" brace is lined up with the header. Everything else inside the braces is indented like this:
public class FirstApplet extends Applet {
// Define your attributes here
// Define your methods here
} |
The advantage of classic style indentation is that you can see more lines of code on your screen at once.
Vertical-style Indenting
In vertical-style indenting, the opening brace is placed on a line of its own instead of on the line that contains the block header. The advantage of vertical-style indenting is that it makes it easy to match all of the begin-end braces in your program, something that is difficult to do using classic indentation.
As you might expect, each opening brace must be matched with a closing brace, otherwise your program will not compile. Here's an example of vertical-style indentation:
public class FirstApplet extends Applet
{
// Define your attributes here
// Define your methods here
} |
How much should the code inside your braces be indented? Probably between 3 and 4 spaces. The default "hard" tab-stop used by programs like Notepad is normally 8 spaces, which makes your programs too hard to read. If you use MS-DOS Edit as your program editor, you should adjust the tab-stops using the Settings menu.
Other Style Issues
Java is a free-form language. That means that statements may span several lines, like this
public
class
FirstApplet
extends
Applet
{
} |
You probably don't want to write code like this, however. You should use whitespace to improve the readability of your programs, not reduce the readability. Try to group related statements together into "paragraphs", and separate such groups from unrelated groups of statement by inserting blank lines and comments.
Since statements can span multiple lines, you may be wondering how the javac compiler tells when a statement is done. Java uses the semicolon [;] to mark the end of a statement, just like C and C++. Note that this is different than Pascal, where a semicolon is used to separate multiple statements.
Comments
Lines that begin with two forward slashes, //, are comment lines; both the slashes and anything following them on the same line are ignored by the compiler. Make sure you don't insert a space between the two slashes, however.
You can also create comments that span multiple lines by using the delimiter /* [a forward slash, immediately followed by an asterisk] to start the comment, and the delimiter */ [an asterisk immediately followed by a forward slash] to end the comment. You cannot have multi-line comments inside other multi-line comments, but the single line variety work just fine.
Here's an example of a multi-line comment, along with some whitespace:
/* --------------------------------
FirstApplet.java
Created on 6/10/99
CS 170, OCC
Stephen Gilbert
-------------------------------- */
import java.awt.*;
import java.applet.*;
public class FirstApplet extends Applet
{
// Attributes go here
// Methods go here
} |
Now that you've learned about the general structure of a Java program, it's time to take a look at the stuff that goes in between the braces.
Remember that a class definition is made up of attributes and methods. But what is an attribute made of? Well, as you'll see in the next section, attributes are frequently objects.
Please continue to the next section of this lesson.
|