Quiz About [Your topic]

Quiz About [Your topic]

Programming with methods and classes Chapter 7 Spring 2006 CS 101 Aaron Bloomfield 1 Static vs. non-static 2 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(); Instance method Class (i.e. static) method Service provided by a class and it is not associated with a particular object String t = String.valueOf(n); Class method 3 Variables

Instance variable and instance constants Attribute of a particular object Usually a variable Point p = new Point(5, 5); int px = p.x; Instance variable 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;

Class constants 4 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 5 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 + ")";

} } 6 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); } }

7 Static vs. non-static Execution of the code Output is: (a=1,b=3) (a=2,b=3) 8 Static vs. non-static: memory diagram Staticness s = new Staticness t = new s.increment();

t.increment(); t.increment(); System.out.println System.out.println Staticness(); Staticness(); (s); (t); s t Staticness -a=1 0 Staticness

Staticness -a=2 1 0 b 0 3 2 1 9 Program demo StaticTest.java 10

Hondas best commercial cog.mov 11 Conversion.java 12 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 13 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; 14

Conversion implementation Modifier public indicates other classes can use the metho Modifier static indicates the method is a class method public static double fahrenheitToCelsius (double f) { return (f - 32) / 1.8; } } No use of member/instance variables!!! 15 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; } 16 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; } 17 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; } 18 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); 19 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 3.0 4.0 5.0 kilometers = 1.242742384474668 miles liters = 0.7925161570744452 gallons grams = 0.14109584779832166 ounces hectares = 12.355269141746666 acres 20 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 3.0 4.0 5.0 kilometers = 1.24 miles liters = 0.79 gallons grams = 0.14 ounces hectares = 12.36 acres 21

Program Demo Conversion.java 22 Parameter passing 24 Java parameter passing The value is copied to the method Any changes to the parameter are forgotten when the

method returns 25 Java parameter passing Consider the following code: y 5 7 x 5 static void foobar (int y) { y = 7;

formal parameter } public static void main (String[] args) { actual parameter int x = 5; foobar (x); System.out.println(x); } What gets printed? 26 Java parameter passing Consider the following code: y

7" static void foobar (String y) { y = 7; } x 5" formal parameter public static void main (String[] args) { String x = 5; actual parameter foobar (x); System.out.println(x); }

What gets printed? 27 Java parameter passing Consider the following code: static void foobar (Rectangle y) { y.setWidth (10); formal parameter } public static void main (String[] args) { Rectangle x = new Rectangle(); actual parameter foobar (x); System.out.println(x.getWidth()); } y

What gets printed? x width width= =10 0 28 Java parameter passing Consider the following code: static void foobar (Rectangle y) { y = new Rectangle();

y.setWidth (10); formal parameter } public static void main (String[] args) { Rectangle x = new Rectangle(); actual parameter foobar (x); System.out.println(x.getWidth()); } width width= =10 0 y What gets printed? x

width = 0 29 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 30 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 31 Todays demotivators

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; } main() add() x 8.0 y 11.0

result 19.0 - a 8.0 b 11.0 sum 19.0 - product

- 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; } main() multiply() x

88.0 8.0 y 11.0 a 8.0 b 11.0 sum 19.0 product

88.0 - 37 Cubic Tragedy Cubic_tragedy_m640.mov 38 Casting 40 Casting Weve 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? 41

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 its a String (as it cloned a String) Thus, we need to tell Java its a String via casting

Revised code: String s = foo; String t = (String) s.clone(); Still causes that other error, but we are still willfully 42 ignoring it Casting, take 3 That other error is because String does not have a .clone() method Not all classes do!

We just havent seen any classes that do have .clone() yet Check in the documentation if the object you want to copy has a .clone() method A class that does: java.util.Vector Vector s = new Vector(); Vector t = s.clone(); Vector u = (Vector) s.clone(); Causes the inconvertible types

error 43 Casting, take 4 What 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 = (String) v.clone(); Java will encounter a RUN-time error ClassCastException 44 Triple.java 45 Task Triple.java

Represent objects with three integer attributes public Triple() Constructs a default Triple value representing three zeros public Triple(int a, int b, int c) Constructs a representation of the values a, b, and c public int getValue(int i)

Returns the i-th element of the associated Triple public void setValue(int i, int value) Sets the i-th element of the associated Triple to value 46 Task Triple.java Represent objects with three integer attributes public String toString() Returns a textual representation of the associated Triple

public Object clone() Returns a new Triple whose representation is the same as the associated Triple public boolean equals(Object v) Returns whether v is equivalent to the associated Triple 47 Triple.java implementation // Triple(): default constructor public Triple() { this (0, 0, 0); }

The new Triple object (the this object) is constructed by invoking the Triple constructor expecting three int values as actual parameters public Triple() { int a = 0; int b = 0; int c = 0; this (a, b, c); } Illegal this() invocation. A this() invocation must begin its statement body 48 Triple.java implementation // Triple(): default constructor public Triple() { this (0,0,0); }

// Triple(): specific constructor public Triple(int a, int b, int c) { setValue(1, a); setValue(2, b); setValue(3, c); } // Triple(): specific constructor - alternative definition public Triple(int a, int b, int c) { this.setValue(1, a); this.setValue(2, b); this.setValue(3, c); 49 } Triple.java implementation Class Triple like every other Java class Automatically an extension of the standard class Object

Class Object specifies some basic behaviors common to all objects These behaviors are said to be inherited Three of the inherited Object methods toString() clone() equals() 50 Recommendation

Classes should override implementation) toString() clone() equals() (i.e., provide a class-specific By doing so, the programmer-expected behavior can be

provided System.out.println(p); // displays string version of // object referenced by p System.out.println(q); // displays string version of // object referenced by q 51 Triple.java toString() implementation public int int int String toString() { a = getValue(1); b = getValue(2); 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); Produces Triple[10, 20, 30] Triple[8, 88, 888] 52 Triple.java clone() implementation public int int

int Object clone() { a = getValue(1); b = getValue(2); c = getValue(3); return new Triple(a, b, c); } Consider Triple t1 = new Triple(9, 28, 29); Triple t2 = (Triple) t1.clone(); Must cast! System.out.println("t1 = " + t1); System.out.println("t2 = " + t2);

Produces Triple[9, 28, 29] Triple[9, 28, 29] 53 Triple.java equals() implementation public boolean equals(Object v) { if (v instanceof Triple) { int a1 = getValue(1); int b1 = getValue(2); int c1 = getValue(3); Triple int a2 int b2 int c2 t =

= = Cant be equal unless its a Triple = (Triple) v; t.getValue(1); t.getValue(2); t.getValue(3); return (a1 == a2) && (b1 == b2) && (c1 == c2); } else { return false; } Compare corresponding attributes

} 54 Triple.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 flag1 = e.equals(f); e f g h Triple x1: 4

x2: 6 x3: 10 Triple x1: 4 x2: 6 x3: 11 Triple x1: 4 x2: 6 Triple x1: 4 x2: 5

x3: 10 55 x3: 11 Triple.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); e f g h

Triple x1: 4 x2: 6 x3: 10 Triple x1: 4 x2: 6 x3: 11 Triple x1: 4 x2: 6 Triple

x1: 4 x2: 5 x3: 10 56 x3: 11 Triple.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 flag3 = g.equals(h); e f

g h Triple x1: 4 x2: 6 x3: 10 Triple x1: 4 x2: 6 x3: 11 Triple

x1: 4 x2: 6 Triple x1: 4 x2: 5 x3: 10 57 x3: 11 Using our Triple class

58 Program demo TripleDemo.java 59 Scope 60 Whats wrong with this code? class Scope { public static void f(int a) { int b = 1; // local definition System.out.println(a); // print 10 a = b;

// update a System.out.println(a); // print 1 } public static void main(String[] args) { int i = 10; // local definition f(i); // invoking f() with i as parameter System.out.println(a); System.out.println(b); } } 61 Variables a and b do not exist in the scope of method main() Program demo Scope.java (just the compilation)

62 Blocks and scope rules A block is a list of statements nested within braces A method body is a block A block can be placed anywhere a statement would be legal A block contained within another block is a nested block A formal parameter is considered to be defined at the beginning of the method body

A local variable can be used only in a statement or nested blocks that occurs after its definition An identifier name can be reused as long as the blocks containing the duplicate declarations are not nested one within the other Name reuse within a method is permitted as long as the reuse occurs in distinct blocks 63 Legal class Scope2 { public static void main(String[] args) { int a = 10; f(a); System.out.println(a);

} public static void f(int a) { System.out.println(a); a = 1; System.out.println(a); } } 64 Legal but not recommended public void g() { { int j = 1; System.out.println(j); } { int j = 10; System.out.println(j); }

{ char j = '@'; System.out.println(j); } } // define j // print 1 // define a different j // print 10 // define a different j // print '@' 65 Program demo

Scope2.java (just the compilation) 66 Whats the output? for (int i = 0; i < 3; ++i) { int j = 0; ++j; System.out.println(j); } The scope of variable j is the body of the for loop j is not in scope when ++i j is not in scope when i < 3 are evaluated j is redefined and re-initialized with each loop iteration

67 Overloading 68 Overloading Have seen it often before with operators int i = 11 + 28; double x = 6.9 + 11.29; String s = "April " + "June"; Java also supports method overloading Several methods can have the same name

Useful when we need to write methods that perform similar tasks but different parameter lists Method name can be overloaded as long as its signature is different from the other methods of its class Difference in the names, types, number, or order of the parameters 69 Legal public static int min(int a, int b, int c) { return Math.min(a, Math.min(b, c)); } public static int min(int a, int b, int c, int d) { return Math.min(a, min(b, c, d)); } 70

Legal public static int power(int x, int n) { int result = 1; for (int i = 1; i <= n; ++i) { result *= x; } return result; } public static double power(double x, int n) { double result = 1; for (int i = 1; i <= n; ++i) { result *= x; } return result; } 71 Whats the output? public static void f(int a, int b) {

System.out.println(a + b); } public static void f(double a, double b) { System.out.println(a - b); } public static void main(String[] args) { int i = 19; double x = 54.0; f(i, x); } 72 Summary 73 Summary of key points

The this keyword Can be used to call another constructor Must be the FIRST thing called Can be used as a reference to the current object Static vs. non-static A static variable means there is only one such variable regardless of how many objects have been declared A static method does not care about the state of the object Various methods we may want to override:

clone() toString() equals() 74 Using random numbers

Recently Viewed Presentations

  • New Student Orientatio n ss a l C

    New Student Orientatio n ss a l C

    The FSA End-of-Course (EOC) Assessments Algebra I, Geometry, Biology, and US History will be administered during the month of May of 2020. AP and IB exams will be administered in May 2020. Specific testing dates for 2019 - 2020 will...
  • collegiate.dsbn.org

    collegiate.dsbn.org

    Select & change answers. Getting Started... Logging On and Signing In: On the day of the OSSLT testing, Log onto a DSBN device using your DSBN credentials. Click on the EQAO Online Kiosk App on your desktop. ... Practice using...
  • Quantum One 1  2 Identical Particles  3 Identical

    Quantum One 1 2 Identical Particles 3 Identical

    Field Operators and Second Quantization. In this final segment on identical particles we have completed the path that we started at the beginning of the course, which began with a review of the quantum mechanics of a singlespin-less particle, in...
  • PowerPoint bemutató

    PowerPoint bemutató

    Folyamatosan frissülnek, akár heti rendszerességgel. Teljesen elfedik a HTTP layert. Csak C# Azure erőforrás objektum be és kimenetű függvények vannak. Egymásra épülő erőforrások létrehozhatóak egyetlen kérésben. VM, NIC, IP cím esetén már a teljes objektum fa megadható
  • GPS IIR-20 (SVN-49) Panel Discussion

    GPS IIR-20 (SVN-49) Panel Discussion

    GPS IIR-20 (SVN-49) Information 25 January 2010 Col David Goldstein Chief Engineer, GPS Wing ... Dual frequency ionosphere refraction corrected pseudoranges Relative to "best fit" orbit during initial test period (6 April 2009) Roughly 4+ meter spread from 10 to...
  • Social Influence - RowenaT

    Social Influence - RowenaT

    Social Influence The exercise of social power by a person or group to change the attitude or behavior of others in a particular direction Classic Conformity Research Sherif : Conformity in an ambiguous reality Autokinetic effect Asch: Conformity in a...
  • Clinical Trial Quality and Compliance: An FDA Perspective

    Clinical Trial Quality and Compliance: An FDA Perspective

    * * Ni A. Khin, M.D. Medical Officer Division of Scientific Investigations Office of Medical Policy Division of Scientific Investigations Center for Drug Evaluation and Research Office of the Center Director Janet Woodcock, M..D. Director Office of Medical Policy Robert...
  • External Respiration - Specifics

    External Respiration - Specifics

    External Respiration: Reasons for Difference humidification of inhaled air gas movements increases alveolar PCO2 decreases alveolar PO2 mixing of old and new air (not all alveolar air is exchanged with each breath) External Respiration: Gas Movements O2 loading (into blood)...