1 / 93

Programming with methods and classes

Programming with methods and classes. Chapter 7 Fall 2005 CS 101 Aaron Bloomfield. Static vs. non-static. Methods. Instance (or member) method Operates on a object (i.e., and instance of the class) String s = new String("Help every cow reach its " + "potential!"); int n = s.length();

moana
Download Presentation

Programming with methods and classes

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Programming withmethods and classes Chapter 7 Fall 2005 CS 101 Aaron Bloomfield

  2. Static vs. non-static

  3. Methods • Instance (or member) method • Operates 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) method • Service provided by a class and it is not associated with a particular object String t = String.valueOf(n); Instance method Class method

  4. Variables • Instance variable and instance constants • Attribute of a particular object • Usually a variable Point p = new Point(5, 5); int px = p.x; • Class variables and constants • Collective information that is not specific to individual objects of the class • Usually a constant Color favoriteColor = Color.MAGENTA; double favoriteNumber = Math.PI - Math.E; Instance variable Class constants

  5. static and non-static rules • Member/instance (i.e. non-static) fields and methods can ONLY be accessed by the object name • Class (i.e. static) fields and methods can be accessed by Either the class name or the object name • Non-static methods can refer to BOTH class (i.e. static) variables and member/instance (i.e. non-static) variables • Class (i.e. static) methods can ONLY access class (i.e. static) variables

  6. Static vs. non-static • Consider 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 + ")"; } }

  7. Static vs. non-static • And the code to run it: public class StaticTest { public static void main (String[] args) { Staticness s = new Staticness(); Staticness t = new Staticness(); s.increment(); t.increment(); t.increment(); System.out.println (s); System.out.println (t); } }

  8. Static vs. non-static • Execution of the code… • Output is: (a=1,b=3) (a=2,b=3)

  9. t s Staticness Staticness Staticness Staticness Staticness • a = 0 • a = 1 • a = 1 • a = 2 • a = 0 Static vs. non-static: memory diagram Staticness s = new Staticness(); Staticness t = new Staticness(); 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); 1 0 2 3 b

  10. Program demo • StaticTest.java

  11. Yale vs. Harvard • Web references: http://www.harvardsucks.org/, http://www.yaledailynews.com/article.asp?AID=27506

  12. Conversion.java

  13. Task – Conversion.java • Support conversion between English and metric values • d degrees Fahrenheit = (d – 32)/1.8 degrees Celsius • 1 mile = 1.609344 kilometers • 1 gallon = 3.785411784 liters • 1 ounce (avdp) = 28.349523125 grams • 1 acre = 0.0015625 square miles = 0.40468564 hectares

  14. Conversion Implementation public class Conversion { // conversion equivalencies private static final double KILOMETERS_PER_MILE = 1.609344; private static final double LITERS_PER_GALLON = 3.785411784; private static final double GRAMS_PER_OUNCE = 28.349523125; private static final double HECTARES_PER_ACRE = 0.40468564;

  15. Modifier public indicates other classes can use the method Modifier static indicates the method is a class method No use of member/instance variables!!! Conversion implementation public static double fahrenheitToCelsius (double f) { return (f - 32) / 1.8; } }

  16. Conversion Implementation // temperature conversions methods public static double fahrenheitToCelsius(double f) { return (f - 32) / 1.8; } public static double celsiusToFahrenheit(double c) { return 1.8 * c + 32; } // length conversions methods public static double kilometersToMiles(double km) { return km / KILOMETERS_PER_MILE; }

  17. Conversion Implementation // mass conversions methods public static double litersToGallons(double liters) { return liters / LITERS_PER_GALLON; } public static double gallonsToLiters(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; }

  18. Conversion Implementation // area conversions methods public static double hectaresToAcres(double hectares) { return hectares / HECTARES_PER_ACRE; } public static double acresToHectares(double acres) { return acres * HECTARES_PER_ACRE; }

  19. Conversion use Scanner stdin = new Scanner (System.in); System.out.print("Enter a length in kilometers: "); double kilometers = stdin.nextDouble(); double miles = Conversion.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.out.print("Enter an area in hectares: "); double hectares = stdin.nextDouble(); double acres = Conversion.hectaresToAcres(hectares);

  20. A Conversion use System.out.println(kilometers + " kilometers = " + miles + " miles "); System.out.println(liters + " liters = " + gallons + " gallons"); System.out.println(grams + " grams = " + ounces + " ounces"); System.out.println(hectares + " hectares = " + acres + " acres"); 2.0 kilometers = 1.242742384474668 miles 3.0 liters = 0.7925161570744452 gallons 4.0 grams = 0.14109584779832166 ounces 5.0 hectares = 12.355269141746666 acres

  21. A preferred Conversion use Part of java.text NumberFormat style = NumberFormat.getNumberInstance(); 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) + " ounces"); System.out.println(hectares + " hectares = " + style.format(acres) + " acres"); 2.0 kilometers = 1.24 miles 3.0 liters = 0.79 gallons 4.0 grams = 0.14 ounces 5.0 hectares = 12.36 acres

  22. Program Demo • Conversion.java

  23. Fractals

  24. Parameter passing

  25. Java parameter passing • The value is copied to the method • Any changes to the parameter are forgotten when the method returns

  26. 5 5 7 y x y Java parameter passing • Consider 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 parameter actual parameter

  27. y x “5" “7" Java parameter passing • Consider 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 parameter actual parameter

  28. y x width = 10 width = 0 Java parameter passing • Consider the following code: static void foobar (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 parameter actual parameter

  29. y x width = 10 width = 0 width = 0 Java parameter passing • Consider the following code: static void foobar (Rectangle y) { y = 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 parameter actual parameter

  30. Java parameter passing • The value of the actual parameter gets copied to the formal parameter • This is called pass-by-value • C/C++ is also pass-by-value • Other languages have other parameter passing types • Any changes to the formal parameter are forgotten when the method returns • However, if the parameter is a reference to an object, that object can be modified • Similar to how the object a final reference points to can be modified

  31. Method invocations • Actual parameters provide information that is otherwise unavailable to a method • When a method is invoked • Java sets aside memory for that particular invocation • Called the activation record • Activation record stores, among other things, the values of the formal parameters • Formal parameters initialized with values of the actual parameters • After initialization, the actual parameters and formal parameters are independent of each other • Flow of control is transferred temporarily to that method

  32. Value parameter passing demonstration public class ParameterDemo { 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 = multiply(a, b); System.out.println(a + " * " + b + " = " + product); } }

  33. Value parameter passing demonstration • The file/class is actually called ParameterDemo.java

  34. Program demo • ParameterDemo.java

  35. ParameterDemo.java walkthrough double sum = add(a, b); Initial values of formal parameters come from the actual parameters public static double add (double x, double y) { double result = x + y; return result; }

  36. ParameterDemo.java walkthrough double multiply = multiply(a, b); Initial values of formal parameters come from the actual parameters public static double multiply(double x, double y) { x = x * y; return x; }

  37. PassingReferences.java

  38. PassingReferences.java import 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, 10); System.out.println(p); f(p); System.out.println(p); g(p); System.out.println(p); } }

  39. PassingReferences.java run g() can change the attributes of the object to which p refers

  40. Program demo • PassingReferences.java

  41. PassingReferences.java public static void main(String[] args) { Point p = new Point(10, 10); System.out.println(p); f(p); java.awt.Point[x=10,y=10]

  42. PassingReferences.java public static void f(Point v) { v = new Point(0, 0); }

  43. PassingReferences.java public 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.Point[x=10,y=10] java.awt.Point[x=10,y=10]

  44. PassingReferences.java public static void g(Point v) { v.setLocation(0, 0); }

  45. PassingReferences.java public 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.Point[x=10,y=10] java.awt.Point[x=10,y=10] java.awt.Point[x=0,y=0]

  46. Star Wars Episode 3 Trailer

  47. Star Wars Episode 3 Trailer • That was a edited version • I changed the PG-rated trailer to a G-rated trailer • The original one can be found at http://www.sequentialpictures.com/ • Or Google for “star wars parody”

  48. Casting

  49. Casting • We’ve seen casting before: • double d = (double) 3; • int x = (int) d; • Aside: duplicating an object • String s = “foo”; • String t = s.clone(); • Causes an error: “inconvertible types” • (Causes another error, but we will ignore that one) • What caused this?

  50. Casting, take 2 • .clone() returns an object of class Object (sic) • More confusion: You can also have an object of class Class • Thus, you can have an Object class and a Class object • Got it? • We know it’s a String (as it cloned a String) • Thus, we need to tell Java it’s a String via casting • Revised code: • String s = “foo”; • String t = (String) s.clone(); • Still causes that “other” error, but we are still willfully ignoring it…

More Related