What Objects Are

Objects are created by using a class of objects as a template. The following statements create a class:

public class Modem {
}

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 class Modem {
    int speed;

    public void displaySpeed() {
        System.out.println("Speed: " + speed);
    }
}

The Modem class now should be starting to look like programs you’ve written during Hours 1 through 9. The Modem class begins with a class statement, except that it has public in it. This means that the class is available for use by the public—in other words, by any program that wants to use Modem objects.

The first part of the Modem class creates an integer variable called speed. This variable is an attribute of the object.

The second part of the Modem class 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 speed value.

An object’s variables often are called instance variables or member variables.

If you want to use a Modem object in a program, you create the object with the following statement:

Modem device = new Modem();

This statement creates a Modem object 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 speed variable of the device object:

device.speed = 28800;

To make this modem display its speed by calling the displaySpeed() method, you call the method:

device.displaySpeed();

The Modem object named device would respond to this statement by displaying the text “Speed: 28800.”

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.97.202