OP07第七章Method.ppt

上传人:本田雅阁 文档编号:2202360 上传时间:2019-03-03 格式:PPT 页数:43 大小:267.51KB
返回 下载 相关 举报
OP07第七章Method.ppt_第1页
第1页 / 共43页
OP07第七章Method.ppt_第2页
第2页 / 共43页
OP07第七章Method.ppt_第3页
第3页 / 共43页
亲,该文档总共43页,到这儿已超出免费预览范围,如果喜欢就下载吧!
资源描述

《OP07第七章Method.ppt》由会员分享,可在线阅读,更多相关《OP07第七章Method.ppt(43页珍藏版)》请在三一文库上搜索。

1、1、Java开发类库 2、 static:类变量和类方法 3、 方法-多个参数 4、 数据类型转换 5、 应用举例 6、 作用域 7、 方法重载,第7讲 、Java 方法(Method),1、Java开发类库,“divide and conquer” The best way to develop and maintain a large program is to construct it from small, simple pieces, or modules (模块/组件). Java 有三种 modules - methods, classes and packages Java p

2、rograms are written by combining new methods and classes that the programmer writes with predefined methods and classes available in the Java Application Programming Interface(Java API) and in various other class libraries.,多数编程语言都有预选编译好的类库以支持各种特定的功能 Application Programming Interface (API) 在Java中,类库

3、以包(package)的形式提供 不同版本的Java提供不同的包,以面向特定的应用 Java2平台包括标准版(J2SE)、企业版(J2EE)和微缩版(J2ME)三个版本,Java开发类库,Standard Edition J2SE 包含那些构成Java语言核心 (标准版) 的类。 数据库连接、接口定义、输入/输出、网络编程 Enterprise Edition J2EE 包含J2SE 中的类,并且还包 (企业版) 含用于开发企业级应用的类。 EJB、servlet、JSP、XML、事务控制 Micro Edition J2ME 包含J2SE中一部分类,用于 (微缩版) 消费类电子产品的软件开发

4、。 呼机、智能卡、手机、PDA、机顶盒,Java2的三个版本,Java提供了丰富的标准类来帮助程序设计者更方便快捷地编写程序,这些标准类组成了类包,主要有: java.lang java.awt java.applet java.awt.image java.awt.peer java.io java.util 除了java.lang之外,其余类包都不是java语言所必须的。,J2SE的类包,Language java.lang 构成Java语言核心的类 Object, Math, String, Number, Exception, System, Runtime Utilities ja

5、va.util 提供实用的数据结构 Vector, Stack, Hashtable / Colloection, List, Set, Map I/O java.io 提供多种类型的输出/输出 InputStream, OutputStream, Reader, Writer, RandomAccessFile, File Text java.text 文本/日期/数字/消息的本地化支持 NumberFormat, DateFormat, and Collator Math java.math 提供任意精度的整数和浮点数运算 AWT java.awt 用户接口设计和事件处理 Swing ja

6、vax.swing 提供全Java的,在任何平台上表现 都相同的轻量级构件,J2SE的类包,Javax javax 对Java语言的扩展 Applet java.applet 用于创建Applet的类 Beans java.beans 用于开发JavaBeans的类 Reflection java.lang.reflect 用于动态获取类信息的类 SQL java.sql 提供对数据库中数据的访问和处理 Connection, ResultSet, Statement RMI java.rmi 支持分布式编程 Networking 支持开发网络应用的类 Socket, URL, URLCon

7、nection Security java.security 支持访问控制和信息安全的类 用于访问控制,防止非信任代码执行关键操作 认证相关的类,实现了消息摘要和数字签名与数字认证等,J2SE的类包,(1)java.lang 本类包中包含了各种定义java语言时必须的类,这些类能够以其他类不能使用的方式访问java的内部。任何java程序都将自动引入这个包。其中的类包括: Object类:java中最原始、最重要的类,每个java类都是它的子类,它实现了每个类都必须具有的基本方法。 基本类型包装器:Boolean, Character, Number, Double, Float, Integ

8、er, Long。 String类:字符串类。 Math类:数学函数的集合。 执行线程:类Thread, ThreadGroup, 接口Runable。 异常和错误:类Exception, Error, 接口Throwable。,J2SE的类包,(1)java.lang 运行环境:可以通过类Runtime和System访问外部系统环境。System类的两个常用功能就是访问标准输入/输出流和错误流、退出程序。 其他类:接口Cloneable、运行时的类等。 (2)java.applet Java Applet是Java编程的一个主要魅力,java.applet类包提供了Applet的运行机制以及

9、一些编写Applet非常有用的方法。,J2SE的类包,(3) java.awt 本类包是各种窗口环境的统一界面(AWT代表Abstract Windows Toolkit,即抽象窗口工具包),其中的类使得创建诸如窗口、菜单、滚动条、文本区、按钮以及复选框等图形用户界面(GUI)的元素变得非常容易。 (4) java.awt.image 类包能够以独立于设备的方式加载并过滤位图图象。 (5) java.awt.peer java.awt.peer是全部awt组件的对等对象接口的集合,每个接口都提供了机器相关基本的方法,awt使用这些方法来实现GUI,而不必关心是何种机器或操作系统。,J2SE的类

10、包,(6) java.io Java的输入/输出模式是完全建立在流的基础之上的。流是一种字节从一个地方到另一个地方的单向流动,可以把流附加于文件、管道和通信链路等。 java.io类包中定义的许多种流类通过继承的方式进行组织,其中也包括一些用来访问本地文件系统上的文件的流类。 (7) 类包用来完成与网络相关的功能:URL、WWW连接以及更为通用的Socket网络通信。 (8) java.util java.util类包包含了一些实用类和有用的数据结构,如字典(Dictionary)、散列表(Hashtable)、堆栈(Stack)、向量(Vectro)以及枚举类(Enumeration)等。

11、,J2SE的类包,2、 static:类变量和类方法,静态方法(类方法): Although most methods execute in response to method calls on specific objects, sometimes a method performs a task that does not depend on the contents of any object. Such a method applies to the class in which it is declared as a whole.,ClassName.methodName(argu

12、ments),System.out.println(Math.sqrt(900.0);,Math.sqrt(900.0),ClassName.fieldName,Math.E (2.7182818284590452354),Math.PI (3.14159265358979323846),static 在方法或变量之前,表明它们是属于类的,称为类方法(静态方法)或类变量(静态变量)。若无static修饰,则是实例方法和实例变量。,类变量在各实例间共享,class ABCD char data; static int share_data; class Demo ABCD a,b,c,d; ,类

13、变量的生存期不依赖于对象,其它类可以不用通过创建该类的实例,直接通过类名访问它们。,public class StaticVar public static int number 5; public class OtherClass public void method() int x = StaticVar.number; , static:类变量和类方法,类方法则相当于C语言中的全局函数,其他的类也可以直接通过类名来访问类方法。(Java程序的入口方法main()就是一个类方法),public class GeneralFunction public static int addUp(in

14、t x,int y) return x+y; public class UseGeneral public void method() int a = 9; int b =10; int c = GeneralFunction.addUp(a,b); , static:类变量和类方法,同一个类的实例方法可以访问该类的类变量和类方法; 而类方法只能访问该类的类变量和类方法,不能直接访问实例的变量和方法。, static:类变量和类方法,不正确的引用 class StaticError String mystring=“hello”; public static void main(String

15、args) System.out.println(mystring); 编译时错误信息: nonstatic variable mystring cannot be referenced from a static context “System.out.println(mystring);”。 为什么不正确: 类方法不能直接访问实例变量 。, static:类变量和类方法,解决的办法 1. 将实例变量改成类变量 class NoStaticError static String mystring=“hello”; public static void main(String args) Sy

16、stem.out.println(mystring); , static:类变量和类方法,解决的办法 2. 先创建一个类的实例 class NoStaticError String mystring=“hello”; public static void main(String args) NoStaticError noError; noError = new NoStaticError(); System.out.println(noError.mystring); , static:类变量和类方法,3、 方法-多个参数,/* no ; after( ), otherwise a synt

17、ax error /* ( double x, y, z ) a syntax error public double maximum( double x, double y, double z ) double maximumValue = x; / assume x is the largest to start / determine whether y is greater than maximumValue if ( y maximumValue ) maximumValue = y; / determine whether z is greater than maximumValu

18、e if ( z maximumValue ) maximumValue = z; return maximumValue; / end method maximum,import java.util.Scanner; public class MaximumFinder / obtain three floating-point values and determine maximum value public void determineMaximum() / create Scanner for input from command window Scanner input = new

19、Scanner( System.in ); / prompt for and input three floating-point values System.out.print( “Enter three floating-point values separated by spaces: “ ); double number1 = input.nextDouble(); / read first double double number2 = input.nextDouble(); / read second double double number3 = input.nextDouble

20、(); / read third double / determine the maximum value /* There must be one argument in the method call for each parameter x y z double result = maximum( number1, number2, number3 ); / display maximum value System.out.println( “Maximum is: “ + result ); / end method determineMaximum / returns the max

21、imum of its three double parameters public double maximum( double x, double y, double z ) return maximumValue; / end class MaximumFinder, 使用Math.max实现maximum,/* no ; after( ), otherwise a syntax error /* ( double x, y, z ) a syntax error public double maximum( double x, double y, double z ) return M

22、ath.max(x, Math.max(y, z); / end method maximum,+ 字符串连接,double result = maximum( number1, number2, number3 ); System.out.println( “Maximum is: “ + result );,Every primitive value and object in Java has a String representation. double number will be converted to its String value, any trailing zeros w

23、ill be discarded. boolean will be converted to the String “true” or “false” All objects have a method named toString that returns a String representation of the object.,int y = 5; System.out.println( “y + 2 = “ + y+2 ); /? System.out.println( “y + 2 = “ + (y+2) ); /?,What are the following outputs?,

24、Using method name directly; objectName.methodName(); className.staticMethodName();,When the program flow reaches the method-ending right brace; return; return expression;,Three ways to call a method:,Three ways to return control to the statement that calls a method:,return语句从当前方法中退出,返回到调用该方法的语句处,并从紧

25、跟该语句的下一条语句继续程序的执行。返回语句有两种格式: return expression; /当方法需要返回某种类型数据时 return; /当方法的返回类型为void时 单独一条return语句放在方法中间时,会产生编译错误,因为其后的语句将不会执行到。若真需要退出方法,可以通过将return语句嵌入某些语句(如if-else)来使程序在未执行完方法中所有语句时退出。,基本数据类型 所有基本类型所占的位数都是确定的,并不因操作系统的不同而不同。 所有基本类型的关键词都是小写的。,数据类型 所占位数 数的范围 char 16 0 65535 byte 8 -2727-1 short 16

26、-215215-1 int 32 -231231-1 long 64 -263263-1 f loat 32 3.4e038 3.4e038 double 64 1.7e308 1.7e308,4、 参数(数据)类型转换,自动类型转换 整型、实型、字符型数据可以混合运算。运算中,不同类型的数据先转化为同一类型,然后进行运算,转换从低级到高级: 低-高 byte,short,char int long float double,操作数1类型 操作数2类型 转换后的类型 byte、short、char int int byte、short、char、int long long byte、short

27、、char、int、long float float byte、short、char、int、long、float double double,基本数据类型:数据类型转换,数据类型转换必须满足如下规则: 不能对boolean类型进行类型转换。 不能把对象类型转换成不相关类的对象。 在把容量大的类型转换为容量小的类型时必须使用强制类型转换。 转换过程中可能导致溢出或损失精度 int i = 8; byte b=(byte)i; (byte)255 = -1 (byte)0x5634 = 0x34 浮点数到整数的转换是通过舍弃小数得到,而不是四舍五入 (int)23.7 = 23 (int)-45

28、.89f = -45,System.out.println(Math.sqrt(9);,the int value 9 will be converted to the double value 9.0,5、 应用举例,随机数的产生 使用 object of class Random ( java.util); 使用 Math的静态方法 random( Math.random() ) 。 Objects of class Random can produce random boolean, byte, float, double, in , long and Gaussian values;

29、Math method random can produce only double values in the range of 0.0, 1.0。,Random randomNumbers = new Random(); int randomValue = randomNumbers.nextInt();,Class Random method nextInt() generates a random int value in the range of -2147483648, + 2147483647. The calculation uses the current time of d

30、ay to seed the random number generator. How to use the class Random method nextInt() to generate a required range of values? For example, 0-1, 1-6,/produce random value 0 or 1. int randomValue = randomNumbers.nextInt( 2 );,/produce random value in the range 0-5 int face = randomNumbers.nextInt( 6 );

31、,/produce random value in the range 1-6 int face = 1 + randomNumbers.nextInt( 6 );,?/How to produce random value 2,5,8,11,14,/ How to produce random value 2,5,8,11,14 int face = 2 + 3 * randomNumbers.nextInt( 5 );,You roll two dice(tou zi). Each die has six faces, which contain 1,2,3,4,5 and 6 spots

32、. After the dice have come to rest, the sum of the spots on the two upward faces is calculated. If the sum is 7 or 11 on the first throw , you win(called “craps”). If the sum is 2,3,or 12on the first throw, you lose(the “house” wins). If the sum is 4,5,6,8,9 or 10 on the first throw, that sum become

33、s your “point”. To win, you must continue rolling the dice until you “make your point”(roll that same value.) You lose by rolling a 7 before making the point.,A Game of Chance,public class Craps private Random randomNumbers = new Random(); / enumeration with constants that represent the game status

34、private enum Status CONTINUE, WON, LOST ; / constants that represent common rolls of the dice private final static int SNAKE_EYES = 2; private final static int TREY = 3; private final static int SEVEN = 7; private final static int YO_LEVEN = 11; private final static int BOX_CARS = 12; / plays one ga

35、me of craps public void play() int myPoint = 0; / point if no win or loss on first roll Status gameStatus; / can contain CONTINUE, WON or LOST int sumOfDice = rollDice(); / first roll of the dice / determine game status and point based on first roll switch ( sumOfDice ) case SEVEN: / win with 7 on f

36、irst roll case YO_LEVEN: / win with 11 on first roll gameStatus = Status.WON; break; case SNAKE_EYES: / lose with 2 on first roll case TREY: / lose with 3 on first roll case BOX_CARS: / lose with 12 on first roll gameStatus = Status.LOST; break; default: / did not win or lose, so remember point game

37、Status = Status.CONTINUE; / game is not over myPoint = sumOfDice; / remember the point System.out.printf( “Point is %dn“, myPoint ); break; / optional at end of switch / end switch,/ while game is not complete while ( gameStatus = Status.CONTINUE ) / not WON or LOST sumOfDice = rollDice(); / roll di

38、ce again / determine game status if ( sumOfDice = myPoint ) / win by making point gameStatus = Status.WON; else if ( sumOfDice = SEVEN ) / lose by rolling 7 before point gameStatus = Status.LOST; / end while / display won or lost message if ( gameStatus = Status.WON ) System.out.println( “Player win

39、s“ ); else System.out.println( “Player loses“ ); / end method play,/ continue with the above program / roll dice, calculate sum and display results public int rollDice() / pick random die values int die1 = 1 + randomNumbers.nextInt( 6 ); / first die roll int die2 = 1 + randomNumbers.nextInt( 6 ); /

40、second die roll int sum = die1 + die2; / sum of die values / display results of this roll System.out.printf( “Player rolled %d + %d = %dn“, die1, die2, sum ); return sum; / return sum of dice / end method rollDice / end class Craps,public class CrapsTest public static void main( String args ) Craps

41、game = new Craps(); game.play(); / play one game of craps / end main / end class CrapsTest,6、 作用域,作用域(Scope)决定了变量可使用的范围 全局变量(Global variables):变量可以在整个类中被访问; 局部变量( Local variables ):变量只能在定义其的代码段中被访问。 作用域规则:在一个代码段中定义的变量只能在该代码段或者该代码段的子代码段中可见。 使用局部变量比使用全局变量更安全。,class Scoping int x = 0; void method1() in

42、t y; y = x; / OK. method1可以访问y. void method2() int z = 1; z = y; / Error. y 在method2的作用域之外定义 ,作用域,/ Fig. 6.11: Scope.java public class Scope / field that is accessible to all methods of this class private int x = 1; / method begin creates and initializes local variable x / and calls methods useLocal

43、Variable and useField public void begin() int x = 5; / methods local variable x shadows field x System.out.printf( “local x in method begin is %dn“, x ); useLocalVariable(); / useLocalVariable has local x useField(); / useField uses class Scopes field x useLocalVariable(); / useLocalVariable reiniti

44、alizes local x useField(); / class Scopes field x retains its value System.out.printf( “nlocal x in method begin is %dn“, x ); / end method begin,/ create and initialize local variable x during each call public void useLocalVariable() int x = 25; / initialized each time useLocalVariable is called Sy

45、stem.out.printf( “nlocal x on entering method useLocalVariable is %dn“, x ); +x; / modifies this methods local variable x System.out.printf( “local x before exiting method useLocalVariable is %dn“, x ); / end method useLocalVariable / modify class Scopes field x during each call public void useField

46、() System.out.printf( “nfield x on entering method useField is %dn“, x ); x *= 10; / modifies class Scopes field x System.out.printf( “field x before exiting method useField is %dn“, x ); / end method useField public static void main( String args ) Scope testScope = new Scope(); testScope.begin(); /

47、 end main / end class Scope,? output,7、 方法重载,方法重载指得是在同一个类中至少有两个方法用同一个名字,但有不同的参数。,例如对于StringBuffer类,它有方法 public StringBuffer append(int i); public StringBuffer append(double d); public StringBuffer append(String s); public StringBuffer append(char str, int offset, int len);,类方法的重载 方法重载即指多个方法可以享有相同的名字

48、。但是这些方法的参数必须不同,或者是参数个数不同,或者是参数类型不同。 例如,要打印不同类型的数据,int, float, String,不需要定义不同名的方法: printInt(int); printFloat(float); printString(String)。 利用方法重载,只需要定义一个方法名:println(),接收不同的参数: println(int); println(float); println(String);,The compiler distinguishes overloaded methods by their signature a combination of the methods name and the number, type and order of it

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 其他


经营许可证编号:宁ICP备18001539号-1