1 programming with methods and classes chapter 7 fall 2006 cs 101 aaron bloomfield

82
1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

Upload: kelley-tucker

Post on 18-Jan-2018

218 views

Category:

Documents


0 download

DESCRIPTION

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

TRANSCRIPT

Page 1: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

1

Programming withmethods and classes

Chapter 7Fall 2006CS 101Aaron Bloomfield

Page 2: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

22

Static vs. non-staticStatic vs. non-static

Page 3: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

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

Page 4: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

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

Page 5: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

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

Page 6: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

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 + ")";

}

}

Page 7: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

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

}}

Page 8: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

8

Static vs. non-static Execution of the code…

Output is:

(a=1,b=3)(a=2,b=3)

Page 9: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

9

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

Static vs. non-static: memory diagram

Staticness- a = 0

t

Staticness- a = 0

s

0b

Staticness- a = 1

Staticness- a = 1

Staticness- a = 2

123

Page 10: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

1010

Program demoProgram demo StaticTest.javaStaticTest.java

Page 11: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

11

How well do you feel How well do you feel you understand static-ness?you understand static-ness?a)a) Very well! This stuff is so easy.Very well! This stuff is so easy.b)b) With a little review, I’ll be good.With a little review, I’ll be good.c)c) Not very well at all.Not very well at all.d)d) I’m so lost. What’s static again?I’m so lost. What’s static again?e)e) I’d rather not answer this question, I’d rather not answer this question,

thanks.thanks.

Page 12: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

1212

Hand PaintingsHand Paintings

Page 13: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

1313

Conversion.javaConversion.java

Page 14: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

14

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

Page 15: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

15

Conversion Implementationpublic class Conversion {

// conversion equivalenciesprivate 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;

Page 16: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

16

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!!!

Page 17: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

17

Conversion Implementation// temperature conversions methodspublic static double fahrenheitToCelsius(double f) {

return (f - 32) / 1.8;}

public static double celsiusToFahrenheit(double c) {return 1.8 * c + 32;

}

// length conversions methodspublic static double kilometersToMiles(double km) {

return km / KILOMETERS_PER_MILE;}

Page 18: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

18

Conversion Implementation// mass conversions methodspublic 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;

}

Page 19: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

19

Conversion Implementation// area conversions methodspublic static double hectaresToAcres(double hectares) {

return hectares / HECTARES_PER_ACRE;}

public static double acresToHectares(double acres) {return acres * HECTARES_PER_ACRE;

}

Page 20: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

20

Conversion useScanner 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);

Page 21: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

21

A Conversion useSystem.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 miles3.0 liters = 0.7925161570744452 gallons4.0 grams = 0.14109584779832166 ounces5.0 hectares = 12.355269141746666 acres

Page 22: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

22

A preferred Conversion useNumberFormat 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 miles3.0 liters = 0.79 gallons4.0 grams = 0.14 ounces5.0 hectares = 12.36 acres

Part of java.text

Page 23: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

2323

Program DemoProgram Demo Conversion.javaConversion.java

Page 24: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

24

How well do you feel How well do you feel you understand you understand

Conversion.java?Conversion.java?a)a) Very well! This stuff is so easy.Very well! This stuff is so easy.b)b) With a little review, I’ll be good.With a little review, I’ll be good.c)c) Not very well at all.Not very well at all.d)d) I’m so lost. What’s a class again?I’m so lost. What’s a class again?e)e) I’d rather not answer this question, I’d rather not answer this question,

thanks.thanks.

Page 25: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

2525

FractalsFractals

Page 26: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

2727

Parameter passingParameter passing

Page 27: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

28

Java parameter passing The value is copied to the method

Any changes to the parameter are forgotten when the method returns

Page 28: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

29

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

Page 29: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

30

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

y

x “5"

“7"

Page 30: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

31

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

y

x width = 0width = 10

Page 31: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

32

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

y

x width = 0

width = 0width = 10

Page 32: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

33

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

Page 33: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

34

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

Page 34: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

35

Value parameter passing demonstrationpublic 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);

}}

Page 35: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

36

Value parameter passing demonstration

The file/class is actually called ParameterDemo.java

Page 36: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

3737

Program demoProgram demo ParameterDemo.javaParameterDemo.java

Page 37: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

38

8.0x

add()

11.0y

-result

8.0x

add()

11.0y

19.0result

ParameterDemo.java walkthrough

8.0a

main()

11.0b

-sum

-product

8.0a

main()

11.0b

19.0sum

-product

double sum = add(a, b);

public static double add (double x, double y) { double result = x + y;return result;

}

Initial values of formal parameterscome from the actual parameters

Page 38: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

39

8.0x

multiply()

11.0y

88.0x

multiply()

11.0y

8.0a

main()

11.0b

19.0sum

-product

8.0a

main()

11.0b

19.0sum

88.0product

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

Page 39: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

40

How well do you feel How well do you feel you understand parameter you understand parameter

passing?passing?a)a) Very well! This stuff is so easy.Very well! This stuff is so easy.b)b) With a little review, I’ll be good.With a little review, I’ll be good.c)c) Not very well at all.Not very well at all.d)d) I’m so lost. What’s a parameter I’m so lost. What’s a parameter

again?again?e)e) I’d rather not answer this question, I’d rather not answer this question,

thanks.thanks.

Page 40: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

4141

Honda’s best commercialHonda’s best commercial cog.movcog.mov

Page 41: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

4242

CastingCasting

Page 42: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

43

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?

Page 43: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

44

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…

Page 44: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

45

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

Page 45: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

46

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

Page 46: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

47

How well do you feel How well do you feel you understand casting?you understand casting?

a)a) Very well! This stuff is so easy.Very well! This stuff is so easy.b)b) With a little review, I’ll be good.With a little review, I’ll be good.c)c) Not very well at all.Not very well at all.d)d) I’m so lost. What’s a parameter I’m so lost. What’s a parameter

again?again?e)e) I’d rather not answer this question, I’d rather not answer this question,

thanks.thanks.

Page 47: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

4848

OverloadingOverloading

Page 48: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

49

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

Page 49: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

50

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

}

Page 50: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

51

Legalpublic 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;

}

Page 51: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

52

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

Page 52: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

53

How well do you feel How well do you feel you understand you understand

overloading?overloading?a)a) Very well! This stuff is so easy.Very well! This stuff is so easy.b)b) With a little review, I’ll be good.With a little review, I’ll be good.c)c) Not very well at all.Not very well at all.d)d) I’m so lost. What’s a parameter I’m so lost. What’s a parameter

again?again?e)e) I’d rather not answer this question, I’d rather not answer this question,

thanks.thanks.

Page 53: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

5454

2004 IOCCC winners2004 IOCCC winners 2004 winners:2004 winners:

– 2004 2004 anonymousanonymous Rendering of a stroked fontRendering of a stroked font– 2004 2004 arachnidarachnid Curses maze displayer/navigator with only line-of-sightCurses maze displayer/navigator with only line-of-sight

visibilityvisibility– 2004 burley 2004 burley A Poker gameA Poker game– 2004 2004 gavaregavare A ray tracerA ray tracer– 2004 gavin 2004 gavin Mini-OSMini-OS– 2004 hibachi 2004 hibachi A CGI capable HTTP serverA CGI capable HTTP server– 2004 2004 hoylehoyle Curses based polynomial graphing with auto-scaleCurses based polynomial graphing with auto-scale– 2004 jdalbec 2004 jdalbec Conway's look'n'say sequence split into elementsConway's look'n'say sequence split into elements– 2004 kopczynski 2004 kopczynski OCR of 8, 9, 10 and 11OCR of 8, 9, 10 and 11– 2004 2004 newbernnewbern Renders arbitary bitmapped fontsRenders arbitary bitmapped fonts– 2004 omoikane 2004 omoikane A CRC inserterA CRC inserter– 2004 schnitzi 2004 schnitzi Editor animationEditor animation– 2004 sds 2004 sds Space/tab/linefeed steganographySpace/tab/linefeed steganography– 2004 vik1 2004 vik1 X Windows car racing gameX Windows car racing game– 2004 vik2 2004 vik2 Calculates prime numbers using only CPPCalculates prime numbers using only CPP

At At http://www1.us.ioccc.org/years.html#2004http://www1.us.ioccc.org/years.html#2004

Page 54: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

5555

ScopeScope

Page 55: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

56

What’s wrong with this code?class Scope {

public static void f(int a) {int b = 1; // local definitionSystem.out.println(a); // print 10a = b; // update aSystem.out.println(a); // print 1

}

public 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 a and b do not exist in the scope of method main()

Page 56: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

5757

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

Page 57: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

58

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

Page 58: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

59

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

}}

Page 59: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

60

Legal but not recommendedpublic void g() {

{int j = 1; // define jSystem.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 '@'}

}

Page 60: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

6161

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

Page 61: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

62

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

Page 62: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

63

How well do you feel How well do you feel you understand scoping?you understand scoping?

a)a) Very well! This stuff is so easy.Very well! This stuff is so easy.b)b) With a little review, I’ll be good.With a little review, I’ll be good.c)c) Not very well at all.Not very well at all.d)d) I’m so lost. What’s a parameter I’m so lost. What’s a parameter

again?again?e)e) I’d rather not answer this question, I’d rather not answer this question,

thanks.thanks.

Page 63: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

6565

Triple.javaTriple.java

Page 64: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

66

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

Page 65: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

67

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

Page 66: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

68

Triple.java implementation// Triple(): default constructor

public Triple() {this (0, 0, 0);

} The new Triple object (the this object) is constructedby 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() invocationmust begin its statement body

Page 67: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

69

Triple.java implementation// Triple(): default constructorpublic Triple() {

this (0,0,0);}

// Triple(): specific constructorpublic 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);

}

Page 68: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

70

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

Page 69: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

71

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

Page 70: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

72

Triple.java toString() 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);

ProducesTriple[10, 20, 30]Triple[8, 88, 888]

Page 71: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

73

Triple.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.out.println("t2 = " + t2);

ProducesTriple[9, 28, 29]Triple[9, 28, 29]

Must cast!

Page 72: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

74

Triple.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 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

Page 73: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

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 flag1 = e.equals(f);

eTriple

x1: 4

f

g

h

x2: 6 x3: 10

Triple

x1: 4 x2: 6 x3: 11

Triple

x1: 4 x2: 6 x3: 10

Triple

x1: 4 x2: 5 x3: 11

Page 74: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

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 flag2 = e.equals(g);

eTriple

x1: 4

f

g

h

x2: 6 x3: 10

Triple

x1: 4 x2: 6 x3: 11

Triple

x1: 4 x2: 6 x3: 10

Triple

x1: 4 x2: 5 x3: 11

Page 75: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

77

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

eTriple

x1: 4

f

g

h

x2: 6 x3: 10

Triple

x1: 4 x2: 6 x3: 11

Triple

x1: 4 x2: 6 x3: 10

Triple

x1: 4 x2: 5 x3: 11

Page 76: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

78

Using our Triple class …

Page 77: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

7979

Program demoProgram demo TripleDemo.javaTripleDemo.java

Page 78: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

80

How well do you feel How well do you feel you understand Triple.java?you understand Triple.java?a)a) Very well! This stuff is so easy.Very well! This stuff is so easy.b)b) With a little review, I’ll be good.With a little review, I’ll be good.c)c) Not very well at all.Not very well at all.d)d) I’m so lost. What’s a parameter I’m so lost. What’s a parameter

again?again?e)e) I’d rather not answer this question, I’d rather not answer this question,

thanks.thanks.

Page 79: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

8181

SummarySummary

Page 80: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

82

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

Page 81: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

8383

Cubic TragedyCubic Tragedy Cubic_tragedy_m640.movCubic_tragedy_m640.mov

Page 82: 1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield

8484

A two legged dog….A two legged dog….