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

Slides:



Advertisements
Similar presentations
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Advertisements

Chapter 7: User-Defined Functions II
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Methods. int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors)
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Road Map Introduction to object oriented programming. Classes
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
1 Chapter 7 User-Defined Methods Java Programming from Thomson Course Tech, adopted by kcluk.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
1 Review for Midterm 3 CS 101 Spring Topic Coverage  Loops Chapter 4  Methods Chapter 5  Classes Chapter 6, Designing and creating classes.
Chapter 7: User-Defined Methods
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Pointer Data Type and Pointer Variables
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
Writing Classes (Chapter 4)
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
The Java Programming Language
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
1 Programming with methods and classes. 2 Methods  Instance (or member) method Operates on a object (i.e., and instance of the class) String s = new.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
1 Programming with methods and classes. 2 Methods  Instance (or member) method Operates on a object (i.e., and instance of the class) String s = new.
Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???
1 Even even more on being classy Aaron Bloomfield CS 101-E Chapter 4+
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
CSC 142 Computer Science II Zhen Jiang West Chester University
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Method Overloading  Methods of the same name can be declared in the same class for different sets of parameters  As the number, types and order of the.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Programming with methods and classes. Methods  Instance method Operates on a object (i.e., and instance of the class) String s = new String("Help every.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Programming with methods and classes Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield.
Attribute - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 12/24/2016.
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
CSE 501N Fall ‘09 03: Class Members 03 September 2009 Nick Leidenfrost.
1 Programming with methods and classes Chapter 7 Spring 2006 CS 101 Aaron Bloomfield.
Chapter 7: Programming with methods and classes..
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
CompSci 230 S Programming Techniques
Modern Programming Tools And Techniques-I
Chapter 7 User-Defined Methods.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Functions II
Java Programming: Guided Learning with Early Objects
Java Primer 1: Types, Classes and Operators
Methods Chapter 6.
CSC240 Computer Science III
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Programming with methods and classes
Chapter 9 Inheritance and Polymorphism
Programming with methods and classes
Group Status Project Status.
Expressions and Assignment
Classes, Objects and Methods
Visibilities and Static-ness
Review for Midterm 3.
Presentation transcript:

1 Programming with methods 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(); 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 Staticness s = new Staticness(); Staticness t = new Staticness(); s.increment(); t.increment(); System.out.println (s); System.out.println (t); Staticness s = new Staticness(); Staticness t = new Staticness(); s.increment(); t.increment(); System.out.println (s); System.out.println (t); Static vs. non-static: memory diagram Staticness - a = 0 t Staticness - a = 0 s 0 b Staticness - a = 1 Staticness - a = 1 Staticness - a =

10 Program demo StaticTest.java StaticTest.java

11 Yale vs. Harvard Web references: Web references:

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 = kilometers 1 gallon = liters 1 ounce (avdp) = grams 1 acre = square miles = hectares

14 Conversion Implementation public class Conversion { // conversion equivalencies private static final double KILOMETERS_PER_MILE = ; private static final double LITERS_PER_GALLON = ; private static final double GRAMS_PER_OUNCE = ; private static final double HECTARES_PER_ACRE = ;

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

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 = miles 3.0 liters = gallons 4.0 grams = ounces 5.0 hectares = acres

21 A preferred Conversion use 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 = acres Part of java.text

22 Program Demo Conversion.java 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 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 y 5 x 5 y 7

27 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 yx “5"“7"

28 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 yx width = 0width = 10

29 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 yx width = 0 width = 10

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 ParameterDemo.java

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

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

37 End of lecture on 28 Nov 2005  Also talked about HW J8

38 PassingReferences.java

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

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

41 Program demo PassingReferences.java PassingReferences.java

42 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 ]

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

44 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 ]

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

46 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=0,y=0]

47 Star Wars Episode 3 Trailer

48 Star Wars Episode 3 Trailer That was a edited version That was a edited version –I changed the PG-rated trailer to a G-rated trailer The original one can be found at The original one can be found at –Or Google for “star wars parody”

49 Casting

50 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?

51 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…

52 Casting, take 3  That “other” error is because String does not have a.clone() method Not all classes do! We just haven’t 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

53 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

54 New 2005 demotivatiors!

55 Wrapper classes

56 What about adding variables to a Vector?  The add method takes an Object as a parameter public void add (Object o) { Although we haven’t seen it yet, this means you can add any object you want to the vector  Primitive types (i.e. variables) are not objects How can they be added?  The solution: wrapper classes!

57 The Integer wrapper class  This 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 = j.intValue();  Pretty annoying syntax – we’ll see how to get around it in a bit…

58 More on wrapper classes  All the primitive types have wrapper classes Usually, the names are just the capitalized version of the type  I.e. Double for double, Byte for byte, etc. Two exceptions: int and char  int has Integer  char has Character

59 More on wrapper classes  Consider this code: int x = 5; vector.add (x); //… int y = vector.get(0);  Does this code work? It shouldn’t  As we are adding a variable (not an object) to a vector But it does work!  Why?

60 Auto-boxing  Java 1.5 will automatically “wrap” a primitive value into it’s wrapper class when needed And automatically “unwrap” a wrapper object into the primitive value  So 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 autoboxing And auto-unboxing (unauto-boxing?) This does not work in Java 1.4 or before

61 More on auto-boxing  Consider 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);

62 Today’s demotivators

63 Triple.java

64 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

65 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

66 Triple.java implementation // Triple(): default constructor publicTriple() { 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 publicTriple() { inta=0; intb =0; intc = 0; this(a, b, c); } Illegal this() invocation. A this() invocation must begin its statement body

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

68 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()

69 Recommendation  Classes should override (i.e., provide a class-specific implementation)  toString()  clone()  equals()  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

70 Triple.java toString() implementation public 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);  Produces Triple[10, 20, 30] Triple[8, 88, 888]

71 A new take on an old song… AlienSong.mpeg AlienSong.mpeg

72 Triple.java clone() implementation public 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.out.println("t2 = " + t2);  Produces Triple[9, 28, 29] Must cast!

73 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 t = (Triple) v; int a2 = t.getValue(1); int b2 = t.getValue(2); int c2 = t.getValue(3); return (a1 == a2) && (b1 == b2) && (c1 == c2); } else { return false; } } Can’t be equal unless it’s a Triple Compare corresponding attributes

74 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);

75 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);

76 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);

77 Using our Triple class ……

78 Program demo TripleDemo.java TripleDemo.java

79 Yet more new demotivators!!!

80 End of lecture on 30 Nov 2005  Won’t be going over the rest of the slides in this set

81 Scope

82 What’s 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); } } Variables a and b do not exist in the scope of method main()

83 Program demo Scope.java (just the compilation) Scope.java (just the compilation)

84 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

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

86 Legal but not recommended public void g() { { int j = 1; // define j System.out.println(j); // print 1 } { int j = 10; // define a different j System.out.println(j); // print 10 } { char j = // define a different j System.out.println(j); // print } }

87 Program demo Scope2.java (just the compilation) Scope2.java (just the compilation)

88 What’s 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

89 Overloading

90 Overloading  Have seen it often before with operators int i = ; double x = ; 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

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

92 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; }

93 What’s 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); }

94 Summary

95 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()  Using random numbers