1.创建对象;
2.使用属性描述对象;
3.确定对象的行为;
4.合并对象;
5.从其他对象继承;
6.转换对象和其他类型的信息。
程序NewRoot2:计算输入数的算数平方根并输出
1 package com.jsample; 2 3 public class NewRoot2 { 4 public static void main(String[] args){ 5 int number = 100; 6 if (args.length > 0){ 7 number = Integer.parseInt(args[0]); 8 } 9 System.out.println("The square root of " 10 + number 11 + " is " 12 + Math.sqrt(number) 13 ); 14 }
输出:
The square root of 169 is 13.0
程序ModemTester:测试下属四个class的功能
1 package com.jsample; 2 3 public class ModemTester { 4 public static void main(String[] args){ 5 CableModem surfBoard = new CableModem(); 6 DslModem gateway = new DslModem(); 7 AcousticModem acoustic = new AcousticModem(); 8 surfBoard.speed = 500000; 9 gateway.speed = 400000; 10 acoustic.speed = 300; 11 System.out.println("Trying the cable modem:"); 12 surfBoard.displaySpeed(); 13 surfBoard.connect(); 14 System.out.println("Trying the DSL modem"); 15 gateway.displaySpeed(); 16 gateway.connect(); 17 System.out.println("Trying the acoustic modem"); 18 acoustic.displaySpeed(); 19 acoustic.connect(); 20 System.out.println("Closing all modems"); 21 surfBoard.disconnect(); 22 gateway.disconnect(); 23 acoustic.disconnect(); 24 } 25 }
下属class:Modem
1 package com.jsample; 2 3 public class Modem { 4 int speed; 5 6 public void displaySpeed(){ 7 System.out.println("Speed: " + speed); 8 } 9 10 public void disconnect(){ 11 System.out.println("Disconnecting to the Internet"); 12 } 13 }
下属class:CableModem
1 package com.jsample; 2 3 public class CableModem extends Modem{ 4 String method = "cable connecttion"; 5 6 public void connect(){ 7 System.out.println("Connecting to the Internet"); 8 System.out.println("Using a " + method); 9 } 10 }
下属class:DslModem
1 package com.jsample; 2 3 public class DslModem extends Modem{ 4 String method = "DSL phone connection"; 5 6 public void connect(){ 7 System.out.println("Connecting to the Internet"); 8 System.out.println("Using a " + method); 9 } 10 }
下属class:AcousticModem
1 package com.jsample; 2 3 public class AcousticModem extends Modem{ 4 String method = "acoustic connection"; 5 6 public void connect(){ 7 System.out.println("Connecting to the Internet"); 8 System.out.println("Using a " + method); 9 } 10 }
输出:
Trying the cable modem:
Speed: 500000
Connecting to the Internet
Using a cable connecttion
Trying the DSL modem
Speed: 400000
Connecting to the Internet
Using a DSL phone connection
Trying the acoustic modem
Speed: 300
Connecting to the Internet
Using a acoustic connection
Closing all modems
Disconnecting to the Internet
Disconnecting to the Internet
Disconnecting to the Internet