Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

124 HOUR 10:Creating Your First Object


What Objects Are
Objects are created by using a class of objects as a template. The following
statements create a class:
public classModem {
}

An object created from this class can’t do anything because it doesn’t have
any attributes or behavior. You need to add those to make the class useful,
as in the following statements:
public classModem {
int speed;

public voiddisplaySpeed() {
System.out.println(“Speed: “+ speed);
}
}

The Modemclassnow should be starting to look like programs you’ve writ-
ten during Hours 1 through 9. The Modemclass begins with a classstate-
ment, except that it has publicin it. This means that the class is available
for use by the public—in other words, by any program that wants to use
Modemobjects.
The first part of the Modemclass creates an integer variable called speed.
This variable is an attribute of the object.
The second part of the Modemclass is a method called displaySpeed().
This method is part of the object’s behavior. It contains one statement,
System.out.println(), which reveals the modem’s speedvalue.
An object’s variables often are called instance variables or member variables.
If you want to use a Modemobjectin a program, you create the object with
the following statement:
Modem device = new Modem();

This statement creates a Modemobject called device. After you have created
an object, you can set its variables and call its methods. Here’s how to set
the value of the speedvariable of the deviceobject:
device.speed = 28800;
Free download pdf