StringvalueOf(n)_第1页
StringvalueOf(n)_第2页
StringvalueOf(n)_第3页
StringvalueOf(n)_第4页
StringvalueOf(n)_第5页
已阅读5页,还剩90页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、Programming withmethods and classesChapter 7Fall 2005CS 101Aaron Bloomfield1Static vs. non-static2MethodsInstance (or member) methodOperates on a object (i.e., and instance of the class)String s = new String(Help every cow reach its + potential!);int n = s.length(); Class (i.e. static) methodService

2、 provided by a class and it is not associated with a particular objectString t = String.valueOf(n);Instance methodClass method3VariablesInstance variable and instance constantsAttribute of a particular objectUsually a variablePoint p = new Point(5, 5);int px = p.x; Class variables and constantsColle

3、ctive information that is not specific to individual objects of the classUsually a constantColor favoriteColor = Color.MAGENTA;double favoriteNumber = Math.PI - Math.E;Instance variableClass constants4static and non-static rulesMember/instance (i.e. non-static) fields and methods can ONLY be accesse

4、d by the object nameClass (i.e. static) fields and methods can be accessed by Either the class name or the object nameNon-static methods can refer to BOTH class (i.e. static) variables and member/instance (i.e. non-static) variablesClass (i.e. static) methods can ONLY access class (i.e. static) vari

5、ables5Static vs. non-staticConsider the following code:public class Staticness private int a = 0;private static int b = 0;public void increment() a+;b+;public String toString() return (a= + a + ,b= + b + );6Static vs. non-staticAnd the code to run it:public class StaticTest public static void main (

6、String args) Staticness s = new Staticness();Staticness t = new Staticness();s.increment();t.increment();t.increment();System.out.println (s);System.out.println (t);7Static vs. non-staticExecution of the codeOutput is:(a=1,b=3)(a=2,b=3)8Staticness s = new Staticness();Staticness t = new Staticness()

7、;s.increment();t.increment();t.increment();System.out.println (s);System.out.println (t);Staticness s = new Staticness();Staticness t = new Staticness();s.increment();t.increment();t.increment();System.out.println (s);System.out.println (t);Static vs. non-static: memory diagramStaticness a = 0 tStat

8、icness a = 0 s0bStaticness a = 1Staticness a = 1Staticness a = 21239Program demoStaticTest.java10Yale vs. HarvardWeb references: http:/, http:/article.asp?AID=2750611Conversion.java12Task Conversion.javaSupport conversion between English and metric valuesd degrees Fahrenheit = (d 32)/1.8 degrees Cel

9、sius1 mile = 1.609344 kilometers1 gallon = 3.785411784 liters1 ounce (avdp) = 28.349523125 grams 1 acre = 0.0015625 square miles = 0.40468564 hectares13Conversion Implementationpublic class Conversion / conversion equivalenciesprivate static final doubleKILOMETERS_PER_MILE = 1.609344;private static

10、final doubleLITERS_PER_GALLON = 3.785411784;private static final doubleGRAMS_PER_OUNCE = 28.349523125;private static final doubleHECTARES_PER_ACRE = 0.40468564;14Conversion implementationpublic static double fahrenheitToCelsius (double f) return (f - 32) / 1.8; Modifier public indicates other classe

11、s can use the methodModifier static indicates the method is a class methodNo use of member/instance variables!15Conversion Implementation/ temperature conversions methodspublic static double fahrenheitToCelsius(double f) return (f - 32) / 1.8;public static double celsiusToFahrenheit(double c) return

12、 1.8 * c + 32;/ length conversions methodspublic static double kilometersToMiles(double km) return km / KILOMETERS_PER_MILE;16Conversion Implementation/ mass conversions methodspublic static double litersToGallons(double liters) return liters / LITERS_PER_GALLON;public static double gallonsToLiters(

13、double gallons) return gallons * LITERS_PER_GALLON;public static double gramsToOunces(double grams) return grams / GRAMS_PER_OUNCE;public static double ouncesToGrams(double ounces) return ounces * GRAMS_PER_OUNCE;17Conversion Implementation/ area conversions methodspublic static double hectaresToAcr

14、es(double hectares) return hectares / HECTARES_PER_ACRE;public static double acresToHectares(double acres) return acres * HECTARES_PER_ACRE;18Conversion useScanner stdin = new Scanner (System.in);System.out.print(Enter a length in kilometers: );double kilometers = stdin.nextDouble();double miles = C

15、onversion.kilometersToMiles(kilometers);System.out.print(Enter a mass in liters: );double liters = stdin.nextDouble();double gallons = Conversion.litersToGallons(liters);System.out.print(Enter a mass in grams: );double grams = stdin.nextDouble();double ounces = Conversion.gramsToOunces(grams);System

16、.out.print(Enter an area in hectares: );double hectares = stdin.nextDouble();double acres = Conversion.hectaresToAcres(hectares);19A Conversion useSystem.out.println(kilometers + kilometers = + miles + miles );System.out.println(liters + liters = + gallons + gallons);System.out.println(grams + grams

17、 = + ounces + ounces);System.out.println(hectares + hectares = + acres + acres);2.0 kilometers = 1.242742384474668 miles3.0 liters = 0.7925161570744452 gallons4.0 grams = 0.14109584779832166 ounces5.0 hectares = 12.355269141746666 acres20A preferred Conversion useNumberFormat style = NumberFormat.ge

18、tNumberInstance();style.setMaximumFractionDigits(2);style.setMinimumFractionDigits(2);System.out.println(kilometers + kilometers = + style.format(miles) + miles );System.out.println(liters + liters = + style.format(gallons) + gallons);System.out.println(grams + grams = + style.format(ounces) + ounce

19、s);System.out.println(hectares + hectares = + style.format(acres) + acres);2.0 kilometers = 1.24 miles3.0 liters = 0.79 gallons4.0 grams = 0.14 ounces5.0 hectares = 12.36 acresPart of java.text21Program DemoConversion.java22Fractals23Parameter passing24Java parameter passingThe value is copied to th

20、e methodAny changes to the parameter are forgotten when the method returns25Java parameter passingConsider the following code:static void foobar (int y) y = 7;public static void main (String args) int x = 5;foobar (x);System.out.println(x);What gets printed?formal parameteractual parametery5x5y726Ja

21、va parameter passingConsider the following code:static void foobar (String y) y = “7”;public static void main (String args) String x = “5”;foobar (x);System.out.println(x);What gets printed?formal parameteractual parameteryx“5“727Java parameter passingConsider the following code:static void foobar (

22、Rectangle y) y.setWidth (10);public static void main (String args) Rectangle x = new Rectangle();foobar (x);System.out.println(x.getWidth();What gets printed?formal parameteractual parameteryxwidth = 0width = 1028Java parameter passingConsider the following code:static void foobar (Rectangle y) y =

23、new Rectangle();y.setWidth (10);public static void main (String args) Rectangle x = new Rectangle();foobar (x);System.out.println(x.getWidth();What gets printed?formal parameteractual parameteryxwidth = 0width = 0width = 1029Java parameter passingThe value of the actual parameter gets copied to the

24、formal parameterThis is called pass-by-valueC/C+ is also pass-by-valueOther languages have other parameter passing typesAny changes to the formal parameter are forgotten when the method returnsHowever, if the parameter is a reference to an object, that object can be modifiedSimilar to how the object

25、 a final reference points to can be modified30Method invocationsActual parameters provide information that is otherwise unavailable to a methodWhen a method is invokedJava sets aside memory for that particular invocationCalled the activation recordActivation record stores, among other things, the va

26、lues of the formal parametersFormal parameters initialized with values of the actual parametersAfter initialization, the actual parameters and formal parameters are independent of each otherFlow of control is transferred temporarily to that method31Value parameter passing demonstrationpublic class P

27、arameterDemo public static double add(double x, double y) double result = x + y;return result;public static double multiply(double x, double y) x = x * y;return x;public static void main(String args) double a = 8, b = 11;double sum = add(a, b);System.out.println(a + + + b + = + sum);double product =

28、 multiply(a, b);System.out.println(a + * + b + = + product);32Value parameter passing demonstrationThe file/class is actually called ParameterDemo.java33Program demoParameterDemo.java34ParameterDemo.java walkthroughdouble sum = add(a, b);public static double add (double x, double y) double result =

29、x + y;return result;Initial values of formal parameterscome from the actual parameters35ParameterDemo.java walkthroughdouble multiply = multiply(a, b);public static double multiply (double x, double y) x = x * y;return x;Initial values of formal parameterscome from the actual parameters36End of lect

30、ure on 28 Nov 2005Also talked about HW J837PassingReferences.java38PassingReferences.javaimport java.awt.*;public class PassingReferences public static void f(Point v) v = new Point(0, 0);public static void g(Point v) v.setLocation(0, 0);public static void main(String args) Point p = new Point(10, 1

31、0);System.out.println(p);f(p);System.out.println(p);g(p);System.out.println(p);39PassingReferences.java rung() can change the attributes of the object to which p refers40Program demoPassingReferences.java41PassingReferences.javapublic static void main(String args) Point p = new Point(10, 10);System.

32、out.println(p);f(p);java.awt.Pointx=10,y=1042PassingReferences.javapublic static void f(Point v) v = new Point(0, 0);43PassingReferences.javapublic static void main(String args) Point p = new Point(10, 10);System.out.println(p);f(p);System.out.println(p);g(p);java.awt.Pointx=10,y=10java.awt.Pointx=1

33、0,y=1044PassingReferences.javapublic static void g(Point v) v.setLocation(0, 0);45PassingReferences.javapublic static void main(String args) Point p = new Point(10, 10);System.out.println(p);f(p);System.out.println(p);g(p);System.out.println(p);java.awt.Pointx=10,y=10java.awt.Pointx=10,y=10java.awt.

34、Pointx=0,y=046Star Wars Episode 3 Trailer47Star Wars Episode 3 TrailerThat was a edited versionI changed the PG-rated trailer to a G-rated trailerThe original one can be found at http:/Or Google for “star wars parody”48Casting49CastingWeve seen casting before:double d = (double) 3;int x = (int) d;As

35、ide: duplicating an objectString s = “foo”;String t = s.clone();Causes an error: “inconvertible types”(Causes another error, but we will ignore that one)What caused this?50Casting, take 2.clone() returns an object of class Object (sic)More confusion: You can also have an object of class ClassThus, y

36、ou can have an Object class and a Class objectGot it?We know its a String (as it cloned a String)Thus, we need to tell Java its a String via castingRevised code:String s = “foo”;String t = (String) s.clone();Still causes that “other” error, but we are still willfully ignoring it51Casting, take 3That

37、 “other” error is because String does not have a .clone() methodNot all classes do!We just havent seen any classes that do have .clone() yetCheck in the documentation if the object you want to copy has a .clone() methodA class that does: java.util.VectorVector s = new Vector();Vector t = s.clone();V

38、ector u = (Vector) s.clone();Causes the “inconvertible types” error52Casting, take 4What happens with the following code?Vector v = new Vector();String s = (String) v;Java will encounter a compile-time error“inconvertible types”What happens with the following code?Vector v = new Vector();String s =

39、(String) v.clone();Java will encounter a RUN-time errorClassCastException53New 2005 demotivatiors!54Wrapper classes55What about adding variables to a Vector?The add method takes an Object as a parameterpublic void add (Object o) Although we havent seen it yet, this means you can add any object you w

40、ant to the vectorPrimitive types (i.e. variables) are not objectsHow can they be added?The solution: wrapper classes!56The Integer wrapper classThis is how you add an int variable to a Vector:int x = 5;Integer i = new Integer(x);vector.add (i);/Integer j = (Integer) v.get(0);int y = Value();Pretty a

41、nnoying syntax well see how to get around it in a bit57More on wrapper classesAll the primitive types have wrapper classesUsually, the names are just the capitalized version of the typeI.e. Double for double, Byte for byte, etc.Two exceptions: int and charint has Integerchar has Character58More on w

42、rapper classesConsider this code:int x = 5;vector.add (x);/int y = vector.get(0);Does this code work?It shouldntAs we are adding a variable (not an object) to a vectorBut it does work!Why?59Auto-boxingJava 1.5 will automatically “wrap” a primitive value into its wrapper class when neededAnd automati

43、cally “unwrap” a wrapper object into the primitive valueSo Java translates the previous code into the following:int x = 5;vector.add (new Integer(x);/int y = (Integer)vector.get(0).intValue();This is called autoboxingAnd auto-unboxing (unauto-boxing?)This does not work in Java 1.4 or before60More on

44、 auto-boxingConsider the following code:Double d = 7.5;Double e = 6.5;Double f = d + e;System.println (f);This is doing a lot of auto-boxing (and auto-unboxing):Double d = new Double(7.5);Double e = new Double(6.5);Double f = new Double(d.doubleValue() + e.doubleValue();System.println (f);61Todays d

45、emotivators62Triple.java63Task Triple.javaRepresent objects with three integer attributespublic Triple()Constructs a default Triple value representing three zerospublic Triple(int a, int b, int c)Constructs a representation of the values a, b, and cpublic int getValue(int i)Returns the i-th element

46、of the associated Triplepublic void setValue(int i, int value)Sets the i-th element of the associated Triple to value64Task Triple.javaRepresent objects with three integer attributespublic String toString()Returns a textual representation of the associated Triplepublic Object clone()Returns a new Tr

47、iple whose representation is the same as the associated Triplepublic boolean equals(Object v)Returns whether v is equivalent to the associated Triple 65Triple.java implementation/ Triple(): default constructorpublic Triple() this(0, 0, 0);The new Triple object (the this object) is constructedby invo

48、king the Triple constructor expecting three intvalues as actual parameterspublic Triple() int a = 0;int b = 0;int c = 0;this(a, b, c);Illegal this() invocation. A this() invocationmust begin its statement body66Triple.java implementation/ Triple(): default constructorpublic Triple() this (0,0,0);/ T

49、riple(): specific constructorpublic Triple(int a, int b, int c) setValue(1, a);setValue(2, b);setValue(3, c);/ Triple(): specific constructor - alternative definitionpublic Triple(int a, int b, int c) this.setValue(1, a);this.setValue(2, b);this.setValue(3, c);67Triple.java implementationClass Tripl

50、e like every other Java classAutomatically an extension of the standard class ObjectClass Object specifies some basic behaviors common to all objectsThese behaviors are said to be inheritedThree of the inherited Object methodstoString()clone()equals()68RecommendationClasses should override (i.e., pr

51、ovide a class-specific implementation)toString()clone()equals()By doing so, the programmer-expected behavior can be providedSystem.out.println(p); / displays string version of / object referenced by p System.out.println(q); / displays string version of / object referenced by q 69Triple.java toString

52、() implementationpublic String toString() int a = getValue(1);int b = getValue(2);int c = getValue(3);return Triple + a + , + b + , + c+ ;Consider Triple t1 = new Triple(10, 20, 30);System.out.println(t1);Triple t2 = new Triple(8, 88, 888);System.out.println(t2);ProducesTriple10, 20, 30Triple8, 88,

53、88870A new take on an old songAlienSong.mpeg71Triple.java clone() implementationpublic Object clone() int a = getValue(1);int b = getValue(2);int c = getValue(3);return new Triple(a, b, c);Consider Triple t1 = new Triple(9, 28, 29);Triple t2 = (Triple) t1.clone();System.out.println(t1 = + t1);System

54、.out.println(t2 = + t2);ProducesTriple9, 28, 29Triple9, 28, 29Must cast!72Triple.java equals() implementationpublic boolean equals(Object v) if (v instanceof Triple) int a1 = getValue(1);int b1 = getValue(2);int c1 = getValue(3);Triple t = (Triple) v;int a2 = t.getValue(1);int b2 = t.getValue(2);int

55、 c2 = t.getValue(3);return (a1 = a2) & (b1 = b2) & (c1 = c2);else return false;Cant be equal unless its a TripleCompare corresponding attributes73Triple.java equals()Triple e = new Triple(4, 6, 10);Triple f = new Triple(4, 6, 11);,Triple g = new Triple(4, 6, 10); Triple h = new Triple(4, 5, 11); boo

56、lean flag1 = e.equals(f);74Triple.java equals()Triple e = new Triple(4, 6, 10);Triple f = new Triple(4, 6, 11);,Triple g = new Triple(4, 6, 10); Triple h = new Triple(4, 5, 11); boolean flag2 = e.equals(g);75Triple.java equals()Triple e = new Triple(4, 6, 10);Triple f = new Triple(4, 6, 11);,Triple

57、g = new Triple(4, 6, 10); Triple h = new Triple(4, 5, 11); boolean flag3 = g.equals(h);76Using our Triple class77Program demoTripleDemo.java78Yet more new demotivators!79End of lecture on 30 Nov 2005Wont be going over the rest of the slides in this set80Scope81Whats wrong with this code?class Scope

58、public static void f(int a) int b = 1; / local definitionSystem.out.println(a); / print 10a = b; / update aSystem.out.println(a); / print 1public static void main(String args) int i = 10; / local definitionf(i); / invoking f() with i as parameterSystem.out.println(a); System.out.println(b);Variables

59、 a and b do not exist in the scope of method main()82Program demoScope.java (just the compilation)83Blocks and scope rulesA block is a list of statements nested within bracesA method body is a blockA block can be placed anywhere a statement would be legalA block contained within another block is a n

60、ested blockA formal parameter is considered to be defined at the beginning of the method bodyA local variable can be used only in a statement or nested blocks that occurs after its definitionAn identifier name can be reused as long as the blocks containing the duplicate declarations are not nested o

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论