Lesson 2.4 Creating Objects
In the previous section, you learned about the basic structure of a Java program. In this section, you'll "fill in the blanks" [so to speak] as you learn to define the attributes and behavior of your new class.
Defining Attributes
The first step in creating a new class is to define attributes. In Java this is done by creating fields or instance variables. A field is simply a storage location where you'll store each object's state.
If you created a Car class, for instance, you might create a field to hold each Car object's color. The actual color--red or blue--is the state of each of the individual cars. Each field you define can hold only one particular type of thing. With your Car class, you couldn't use the color field to hold information about each Car's gas mileage.
Instead of going on about Cars, however, let's return to our actual applet. [This is slightly modified from the version used in the Using the JDK lesson]:
|
Listing 1: FirstApplet.java
|
import java.awt.*;
import java.applet.*;
public class FirstApplet extends Applet
{
// Attributes go here
Label theLabel = new Label("Hi Mom!");
// Methods go here
public void init()
{
add(theLabel);
}
} |
As you can see, the only attribute in FirstApplet is a Label object, one of the core classes supplied with Java. The Label class is part of Java's Abstract Window Toolkit or AWT. [Now you can see why FirstApplet has two import statements]
|
What are Peers?
|
| The AWT provides a set of common user-interface objects such as Labels, Buttons, Lists, and so forth. You'll use several of these objects as you complete homework assignment 2. When you create an AWT Button, what Java does is to ask the underlying user-interface [X Windows, MacOS, or Windows] to create a native button, called a peer. The result of this is that when your Java program runs on a Mac, all the Buttons look like Mac buttons; when it runs on Windows, all the Buttons look like Windows buttons. |
The Label class defines a class of objects that:
- can hold a single line of text.
- know how to display themselves
- can be positioned and moved around the screen.
- contains a surprising amount of information about their appearance, such as font size, text color, alignment, and so on.
Attribute Definition Syntax
When you create a field, you define it by explicitly describing three things:
- What kind of thing will be stored in the field
- What name you want to use for the field
- What initial value the field should have
Let's walk through these three easy steps, one-by-one:
Step 1: Start with a class or type
The first step, you recall is to describe what kind of thing will be stored in the field. Thus, the first part of any field definition is a class or type name like this:
Step 2: Give your field a name
You can't send an object a message if you don't know its name. You can make up any name you like, as long as you obey the rules for naming identifiers, like this:
Label bigLabel …
Button okButton …
Frog kermit … |
Step 3: Assign a value to your field
To store a value in your new field you use the assignment operator [=]. The assignment operator copies the value on its right, and stores it in the object on its left.
Label bigLabel = <make Label here>
Button okButton = <make Button here>
Frog kermit = <make Frog here> |
Constructing An Object
At this point, we're kind of in a quandry. How do we create an object? What do we put on the right-hand-side of the assignment operator? If our fields were numbers or characters, for instance, we'd expect to do something like this:
Since our fields are objects, however, we need to learn how to construct an object; we can't just use a literal value like 27. Fortunately, constructing an object is easy. To construct an object--any object--you just use a constructor, along with the keyword new.
If a class represents a blueprint that describes the attributes and methods of an object, then the constructor is the factory that creates the goods. To make things even easier, a constructor always has the same name as the thing you're trying to create. Now we can finish what we started:
Label bigLabel = new Label(“BiiiG”);
Button okButton = new Button(“OK”);
Frog kermit = new Frog(Color.green); |
Some Final Details
The first thing you should notice is that every definition ends in a semicolon. Although it was mentioned before, I should reiterate that every Java statement ends with a semicolon. If you omit the semicolons in these statements, the code will not compile.
The second thing you should notice is the parentheses following the constructor names. Constructors are like methods because they perform an action. In Java, every name that performs an action must be followed by parentheses.
Look again at the code in the example. Do you notice that the word Label appears twice? The first time, the word is not followed by parentheses, so you are not telling the compiler to do anything; the second time, the word is followed by parentheses. This tells the compiler to perform the code contained in the Label constructor.
Finally, notice that each of the constructors has a value inside its parentheses. These values are called arguments. Arguments allow a constructor--or any other method--to customize its operation. That's how the same Frog constructor can be used to turn out turquoise and fucia frogs as well as the prosaic green variety and how the Label class can turn out labels that say something other than "Hi Mom."
|
Attribute Recap
|
You must define every attribute like this:
- Begin with the class name
- Name your field, subject to rules and conventions
- Create a new object using new and a constructor
- Constructor will have same name as class
- Customize by passing arguments in parentheses
|
Defining Methods
An object's methods are where the real action takes place. The Java Applet class has several predefined methods and since our example program FirstApplet is a child of Applet, so to speak, it inherits those methods.
Of course, a method is of no use at all until someone invokes it. In the case of the Applet class and its offspring, that someone is your Web browser. When your Web browser loads a Web page that contains an instance of FirstApplet [defined in an APPLET tag, of course], it first creates a FirstApplet object, and then sends that object predefined set of messages:
| init() |
Sent to the Applet object when after it is first created. |
| start() |
Sent to the Applet object every time the Web page containing the applet is loaded. If the Applet object has already been created, then init() will not be called again before start() |
| stop() |
Sent to the Applet object when the user has left the Web page containing the applet. The applet is not destroyed at this point, and does not even have to stop running. |
| paint() |
Sent to the Applet object when the applet is first displayed and thereafter whenever the browser determines that the surface of the applet needs repainting [after a scroll, for instance]. |
| destroy() |
Sent to the Applet object whenever the browser decides it needs to reclaim the space that the applet is occupying. |
Because FirstApplet is a child of Applet, it automatically inherits all of these methods, which are predefined, inside the Applet class. Unfortunately, the predefined versions don't do anything interesting, so for all of your applets you'll simply redefine (or override) the appropriate methods. We'll start by overrriding init().
Defining New Methods
Methods are defined inside a class definition like this:
import java.awt.*;
import java.applet.*;
public class FirstApplet extends Applet
{
// Attributes go here
Label theLabel = new Label("Hi Mom!");
// Methods go here
public void init()
{
add(theLabel);
}
} |
Notice that the entire method is defined inside the class body, and that a method definition, like a class definition, consists of two parts: a header and a body.
The Method Header
This method header consists of these four pieces:
- public: This is called the access specifier and it means that objects from different classes are free to ask a FirstApplet object to perform this action. If the method were private, then only FirstApplet objects would be able to invoke the method.
- void: The access specifier is followed by the method return type. Every method can, potentially, produce a single value. If the init() method produced a value, we'd put the type of that value [number, character, etc] here. If a method produces no value--like init() --you have to say so by using a return type of void.
- init: This is the name of the method. Because the Applet class already has an init() method and because we want to replace the fairly useless Applet init() method with our own, we must be careful to spell this exactly as shown. Writing Init() or INIT() will not create an error, but your method won't be called either. Your Web browser will call the init() method, and it's very particular about the spelling.
- (...): Every method definition has a set of parentheses following the method name. If our method required arguments, here's where we would put the definitions for those arguments. The init() method doesn't take any arguments, so we just leave this section blank.
The Method Body
Like the class body, the begin and end of a method body are marked by braces. Inside the braces are statements that perform actions. Each time the method is activated [invoked], all of the statements inside the method body are performed one by one.
FirstApplet's init() method contains only a single statement; a statement that simply adds theLabel to the surface of the applet so that it can be seen.
In the next section, Messages and Events, you'll learn how to communicate with your objects by sending them other messages and how your objects can communicate with you by triggering events.
Something to Talk About
Now you know how to add attributes and methods to your classes, try creating a few on your own. Copy the definition for FirstApplet, shown earlier under the subhead Defining New Methods. But, instead of just the one Label field, that's already defined, add three:
- Name each field for one of the Three Stooges.
- Make sure that each Label appears on the surface of the applet.
Oh yeah! Make sure each Label says something appropriate! Please continue to the next section of this lesson.
|