ptg7068951
132 HOUR 10:Creating Your First Object
The following statements show where autoboxing and unboxing come in
handy:
Float total = new Float(1.3F);
float sum = total / 5;
In early versions of Java (before Java 1.5), this would be an error—the use
of a Floatobject in the second statement is not possible. Java now unboxes
totalto make the statement work, resulting in sumbeing equal to 0.26.
Creating an Object
To see aworking example of classes and inheritance, in the next project
you create classes that represent two types of objects: cable modems, which
are implemented as the CableModemclass, and DSLmodems, which are
implemented as the DslModemclass. The workshop focuses on simple
attributes and behavior for these objects:
. Each object should have a speed that it can display.
. Each object should be able to connect to the Internet.
One thing that cable modems and DSLmodems have in common is that
they both have a speed. Because this is something they share, it can be put
into a class that is the superclass of both the CableModemand DslModem
classes. Call this class Modem. In NetBeans, create a new empty Java class
calledModem. Enter Listing 10.2 in the source editor and save the file.
LISTING 10.2 The Full Text of Modem.java
1: public classModem {
2: int speed;
3:
4: public voiddisplaySpeed() {
5: System.out.println(“Speed: “+ speed);
6: }
7: }
This file is compiled automatically as Modem.class. You cannot run this pro-
gram directly, but you can use it in other classes. The Modemclass can handle
one of the things that the CableModemand DslModemclasses have in common.
By using the extendsstatementwhen you are creating the CableModemand
DslModemclasses, you can make each of them a subclass of Modem.
Start a new empty Java file in NetBeans with the class name CableModem.
Enter Listing 10.3 and save the file.