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

(singke) #1
ptg7068951

Creating an Object 133

LISTING 10.3 The Full Text of CableModem.java
1: public classCableModem extendsModem {
2: String method = “cable connection”;
3:
4: public void connect() {
5: System.out.println(“Connecting to the Internet ...”);
6: System.out.println(“Using a “+ method);
7: }
8: }


Create a third file in NetBeans named DslModem. Enter Listing 10.4 and
save the file.


LISTING 10.4 The Full Text of DslModem.java
1: public classDslModem extendsModem {
2: String method = “DSL phone connection”;
3:
4: public voidconnect() {
5: System.out.println(“Connecting to the Internet ...”);
6: System.out.println(“Using a “+ method);
7: }
8: }


If there were no errors, you now have three class files: Modem.class,
CableModem.class, and DslModem.class. However, you cannot run any of
these class files becausethey do not have main()blocks like the ones in
other programs you’ve created. You need to create a short application to
test out the class hierarchy you have just built.


Return to your NetBeans and create a new empty Java file with the class
name ModemTester. Enter Listing 10.5 in the source editor and save the file.


LISTING 10.5 The Full Text of ModemTester.java
1: public classModemTester {
2: public static voidmain(String[] args) {
3: CableModem surfBoard = new CableModem();
4: DslModem gateway = new DslModem();
5: surfBoard.speed = 500000;
6: gateway.speed = 400000;
7: System.out.println(“Trying the cable modem:”);
8: surfBoard.displaySpeed();
9: surfBoard.connect();
10: System.out.println(“Trying the DSL modem:”);
11: gateway.displaySpeed();
12: gateway.connect();
13: }
14: }

Free download pdf