What Objects Are

As stated, objects are created by using a class of objects as a guideline. The following is an example of a class:

public class Modem {
}


Any object created from this class can't do anything because it doesn't have any attributes or behavior yet. You need to add those or this class that won't be terribly useful. You could expand the class into the following:

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


The Modem class now should be recognizable to you because it looks a lot like the programs you have written during Hours 1 through 9. The Modem class begins with a class statement, as your programs have, except that it has a public statement alongside it. The public statement 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 name is one of the things that distinguish a modem from other modems. The second part of the Modem class is a method called displaySpeed(). This method is some of the object's behavior. It contains one statement: a System.out. println() statement that displays the modem's speed value along with some text. If you wanted to use a Modem object in a program, you would create the object much like you would create a variable. You could use the following statement:

Modem com = new Modem();


This statement creates a Modem object called com. You now can use the object in the program; you can set its variables and call its methods. To set the value of the speed variable of the com object, you could use the following statement:

com.speed = 28800;


To make this modem display its speed by calling the displaySpeed() method, you could use the following code:

com.displaySpeed();


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

      
Comments