1 Classes Chapter 4 Fall 2006 CS 101 Aaron Bloomfield.

download 1 Classes Chapter 4 Fall 2006 CS 101 Aaron Bloomfield.

If you can't read please download the document

description

3 Object-oriented programming  Basis Create and manipulate objects with attributes and behaviors that the programmer can specify  Mechanism Classes  Benefits An information type is design and implemented once  Reused as needed No need reanalysis and re-justification of the representation

Transcript of 1 Classes Chapter 4 Fall 2006 CS 101 Aaron Bloomfield.

1 Classes Chapter 4 Fall 2006 CS 101 Aaron Bloomfield 2 Preparation Scene so far has been background material and experience Computing systems and problem solving Variables Types Input and output Expressions Assignments Using objects Standard classes and methods Decisions (if, switch) Loops (while, for, do-while) Next: Experience what Java is really about Design and implement objects representing information and physical world objects 3 Object-oriented programming Basis Create and manipulate objects with attributes and behaviors that the programmer can specify Mechanism Classes Benefits An information type is design and implemented once Reused as needed No need reanalysis and re-justification of the representation 4 Known Classes Classes weve seen BigInteger String Rectangle Vector Scanner System Classes well be seeing soon BigDecimal But the first step is on creating methods 5 Methods 6 Methods weve seen Weve seen methods (functions) before angleSin = Math.sin (90 * PI/180.0); System.out.println (Hello world); value = card.getBlackjackValue(); We are going to start defining them Note that many of these return a value Math.sin() and card.getBlackjack() The way to name methods is the same as variables allTheWordsTogether With the first letter of each word capitalized Except the very first letter is lower case 7 Our first class with methods public class Methods1 { public static void main (String args[]) { Scanner stdin = new Scanner (System.in); System.out.println ("Enter a valid int value"); int value = stdin.nextInt(); if ( value == 1 ) validValue(); else if ( value == 2 ) validValue(); else if ( value == 3 ) invalidValue(); else if ( value == 4 ) invalidValue(); else validValue(); } 8 Our first class with methods, continued public static void invalidValue() { System.out.println ("You have entered an invalid value."); System.out.println ("The program will now exit."); System.exit (0); } public static void validValue() { System.out.println ("You have entered an valid value."); System.out.println ("Congratulations!"); System.out.println ("The program will now exit."); System.exit (0); } 9 Program Demo Methods1.java Methods1.java 10 public static void validValue() { System.out.println ("You have entered an valid value."); System.out.println ("Congratulations!"); System.out.println ("The program will now exit."); System.exit (0); } public static void main (String args[]) { Scanner stdin = new Scanner (System.in); System.out.println ("Enter a valid int value"); int value = stdin.nextInt(); if ( value == 1 ) validValue(); //... } Whats happening there Scanner stdinvalue 1 11 Notes on these methods At this point, all methods in the class are static We will be discussing what static means later in this slide set Until then, Ill be ignoring it, and just telling you when things should and should not be static Sorry! None of those two methods return a value Notice the void before the method name And none take in any parameters Notice the empty parameters after the method name 12 Todays demotivators 13 HW J3 14 Revamping HW J3 Start over Public danger Defense contractor Promoted Cynical guru Become a coder Done tech support? Been a sysadmin? Worked with NT? Want to play w/nukes? Hate people? Bitter yet? Successful managing? Start here Start over A revised HW 3 flowchart Green paths are yes paths, red are no paths Well make a slight modification to the diagram: Note that this part is repeated twice! 15 HW J3 Code The yellow boxed part is what was repeated from the previous slide if ( extractor.askUser(Q_TECH_SUPPORT) ){ if ( extractor.askUser(Q_BITTER_YET) ) if ( extractor.askUser(Q_MANAGEMENT) ) System.out.println (A_CYNICAL); else System.out.println (A_PROMOTED); else System.out.println (A_START_OVER); } else if ( extractor.askUser(Q_BEEN_SYSADMIN) ){ if ( extractor.askUser(Q_HATE_PEOPLE) ) { System.out.println (A_CODER); } else if ( extractor.askUser(Q_WINNT) ){ if ( extractor.askUser(Q_NUCLEAR_WEAPONS) ) System.out.println (A_DEFENSE_CONTRACTOR); else System.out.println (A_PUBLIC_DANGER); } else System.out.println (A_START_OVER); } else if ( extractor.askUser(Q_WINNT) ){ if ( extractor.askUser(Q_NUCLEAR_WEAPONS) ) System.out.println (A_DEFENSE_CONTRACTOR); else System.out.println (A_PUBLIC_DANGER); } else System.out.println (A_START_OVER); 16 HW J3 Code with methods The yellow boxed part is what was repeated from the previous slide if ( extractor.askUser(Q_TECH_SUPPORT) ){ if ( extractor.askUser(Q_BITTER_YET) ) if ( extractor.askUser(Q_MANAGEMENT) ) System.out.println (A_CYNICAL); else System.out.println (A_PROMOTED); else System.out.println (A_START_OVER); } else if ( extractor.askUser(Q_BEEN_SYSADMIN) ){ if ( extractor.askUser(Q_HATE_PEOPLE) ) { System.out.println (A_CODER); } else doBottomPartOfFlowchart(); } else doBottomPartOfFlowchart(); 17 HW J3 Code with methods The doBottomPartOfFlowchart method: public static void doBottomPartOfFlowchart() { if ( extractor.askUser(Q_WINNT) ){ if ( extractor.askUser(Q_NUCLEAR_WEAPONS) ) System.out.println (A_DEFENSE_CONTRACTOR); else System.out.println (A_PUBLIC_DANGER); } else System.out.println (A_START_OVER); } 18 What happened here We took a common set of code Wrote it once But used it multiple times (twice in this case) Granted, the code was a small segment (7 lines) But, in other programs, could be very large This is called Refactoring It is an essential principle of software engineering Has other names: factoring (notice there is no re at the beginning), extracting a method, etc. 19 Pros of Refactoring Benefits of Refactoring Reduce length of code As you dont have to repeat that section of code multiple times Make code easier to read The main if-else-if statement is shorter, thus easier to understand whats going on Changes are easier to make If we want to modify that part of the flowchart, we only have to do it once Rather than searching for each of the repeated code segments in a program 20 Cons of Refactoring Drawbacks of Refactoring Because you are calling another method, it will be slightly slower On the order of a few nanoseconds Modern compilers can sometimes eliminate this penalty The general consensus is that the benefits of Refactoring far outweigh the drawback(s) 21 End of lecture on 11 October 2006 22 Return Values 23 The return keyword The return keyword immediately stops execution of a method And jumps back to whatever called that method And possibly returns a value (well see this next) Consider the following method public static void foo (int x) { if ( x == 1 ) return; System.out.println (x is not 1); } This method will only print the String if x is not 1 24 Return values At some point in those methods, Java must be told to take a value and pass it back Consider angleSin = Math.sin (90 * PI/180.0); At some point in the Math.sin() method, the sin has been computed And that value must be passed back to be stored in angle Consider value = card.getBlackjackValue(); At some point in the card.getBlackjackValue() method, the value has been computed And that value must be passed back to be stored in value This is called returning a value from a method Note that some methods dont return a value System.out.println(), for example 25 Return values (aka return types) public class Methods2 { public static int returnsAValue () { return 1; } public static double alsoReturnsAValue() { return 1.0; } public static void main (String args[]) { int value1 = returnsAValue(); System.out.println (value1); double value2 = alsoReturnsAValue(); System.out.println (value2); // The following line requires a cast int value3 = (int) alsoReturnsAValue(); System.out.println (value3); } } 26 Program Demo Methods2.java Methods2.java 27 Return types All a return statement does is take the value Which could be a number Or a value in a variable Or an expression (such as x+1) And pass it back to whatever called the method 28 How well do you feel you understand return values? a) Very well! This stuff is so easy. b) With a little review, Ill be good. c) Not very well at all. d) Im so lost. Whats a return type again? e) Id rather not answer this question, thanks. 29 Parameters Sometimes you need to pass in parameters to tell a method how to perform Consider Math.sin() it needs to know the angle The parameters are listed between the parenthesis after the method name public static void main (String args[]) The methods we will study next compute (and return) x 2, x 3, and x 4 30 The methods public static int square (int x) { int theSquare = x * x; return theSquare; } public static int cube (int x) { return x * x * x; } public static int fourthPower (int x) { return square(x) * square(x); } 31 A method with multiple parameters public static int squareOrCube (int which, int value) { if ( which == 1 ) return value * value; else if ( which == 2 ) { int cube = value * value * value; return cube; } else return 0; } 32 The main() method import java.util.*; public class Methods3 { // the previous methods go here public static void main (String args[]) { Scanner stdin = new Scanner (System.in); System.out.println ("Enter an int value"); int value = stdin.nextInt(); int theSquare = square(value); System.out.println ("Square is " + theSquare); System.out.println ("Cube is " + cube (value)); System.out.println ("Square is " + squareOrCube (1, value)); System.out.println ("Cube is " + squareOrCube (2,value)); System.out.println ("Fourth power is " + fourthPower (value)); } } 33 Program Demo Methods3.java Methods3.java 34 Ornithology Ornithology Nutrition Nutrition Peace Peace Acoustics Acoustics Mathematics Mathematics Literature Literature Medicine Medicine Physics Physics Chemistry Chemistry Biology Biology The 2006 Ig Nobel Prizes For explaining why woodpeckers dont get headaches For showing that Kuwaiti dung beetles are finicky eaters For development of a high-pitched electronic teen-ager repellent (and, later, ring tones) For experiments to determine why people dont like the sound of fingernails scraping on a blackboard For calculating the number of photos you must take to ensure that (almost) nobody in a group will have their eyes closed For a report entitled, Consequences of Erudite Vernacular Utilized Irrespective of Necessity: Problems with Using Long Words Needlessly. For a medical case report titled, "Termination of Intractable Hiccups with Digital Rectal Massage For studying why dry spaghetti breaks into multiple pieces For a study entitled, Ultrasonic Velocity in Cheddar Cheese as Affected by Temperature," For showing that the female malaria mosquito is equally attracted to the smells of limburger cheese and human feet 35 Returning objects We can also return objects from methods What gets returned is the reference to the object public class Methods4 { public static String getCourse () { String name = "CS 101"; return name; } public static void main (String args[]) { String courseName = getCourse(); System.out.println (courseName); } } String CS 101 courseName name 36 Program Demo Methods4.java Methods4.java 37 Modifying parameters Consider the following code public class Methods5 { public static void changeValue (int x) { x = 7; } public static void main (String args[]) { int y = 5; changeValue(y); System.out.println (y); } } What gets printed? 38 Program Demo Methods5.java Methods5.java 39 Pass by value Java is a pass-by-value language This means that a COPY of the parameters value is passed into the method If a method changes that value, only the COPY is changed Once the method returns, the copy is forgotten And thus the change is not visible outside the method There are other manners of returning values that are used in other languages Pass by reference Pass by name (nobody uses this anymore) We will see about trying to change object parameters later in this slide set 40 How well do you feel you understand parameters? a) Very well! This stuff is so easy. b) With a little review, Ill be good. c) Not very well at all. d) Im so lost. Whats a return type again? e) Id rather not answer this question, thanks. 41 Variable scoping A variable is visible within the block it is declared Called the scope of the variable public class Scoping { static int z public static void foo (int x) { //... } public static void bar () { //... } public static void main (String[] args) { int y; //... } } This local variable is visible until the end of the main() method This variable is visible anywhere in the Scoping class This parameter is visible only in the foo() method 42 Method notes summary You can put the methods in a class in any order Java doesnt care which one is listed first Thus, you can call a method listed later in the method This is different than C/C++ All methods must specify a return type If its void, then no value is returned Parameters cant be changed within a method Although the objects that the parameters point to can be 43 How well do you feel you understand scoping? a) Very well! This stuff is so easy. b) With a little review, Ill be good. c) Not very well at all. d) Im so lost. Whats a return type again? e) Id rather not answer this question, thanks. 44 Todays demotivators 45 The Car class 46 More on classes vs. objects 47 A new example: creating a Car class What properties does a car have in the real world? Color Position (x,y) Fuel in tank We will implement these properties in our Car class public class Car { private Color color; private int xpos; private int ypos; private int fuel; //... } 48 Cars instance variables public class Car { private Color color; private int xpos; private int ypos; private int fuel; //... } + Car - color - fuel - xpos - ypos 49 Instance variables and attributes Default initialization If the variable is within a method, Java does NOT initialize it If the variable is within a class, Java initializes it as follows: Numeric instance variables initialized to 0 Logical instance variables initialized to false Object instance variables initialized to null + Car - color = null - fuel = 0 - xpos = 0 - ypos = 0 50 Car behaviors or methods What can a car do? And what can you do to a car? Move it Change its x and y positions Change its color Fill it up with fuel For our computer simulation, what else do we want the Car class to do? Create a new Car Plot itself on the screen Each of these behaviors will be written as a method 51 Creating a new car To create a new Car, we call: Car c = new Car(); Notice this looks like a method You are calling a special method called a constructor A constructor is used to create (or construct) an object It sets the instance variables to initial values The constructor: public Car() { fuel = 1000; color = Color.BLUE; } 52 Constructors public Car() { fuel = 1000; color = Color.BLUE; } No return type! EXACT same name as class For now, all constructors are public 53 Our Car class so far public class Car { private Color color; private int xpos; private int ypos; private int fuel; public Car() { fuel = 1000; color = Color.BLUE; } } public class Car { private Color color = Color.BLUE; private int xpos; private int ypos; private int fuel = 1000; public Car() { } 54 Our Car class so far public class Car { private Color color = Color.BLUE; private int xpos = 0; private int ypos = 0; private int fuel = 1000; public Car() { } } Called the default constructor The default constructor has no parameters If you dont include one, Java will SOMETIMES put one there automatically + Car() + Car - color = Color.BLUE - fuel = xpos = 0 - ypos = 0 55 Another constructor Another constructor: public Car (Color c, int x, int y, int f) { color = c; xpos = x; ypos = y; fuel = f; } This constructor takes in four parameters The instance variables in the object are set to those parameters This is called a specific constructor An constructor you provide that takes in parameters is called a specific constructor 56 Our Car class so far public class Car { private Color color = Color.BLUE; private int xpos = 0; private int ypos = 0; private int fuel = 1000; public Car() { } public Car (Color c, int x, int y, int f) { color = c; xpos = x; ypos = y; fuel = f; } } + Car() + Car (Color, int, int, int) + Car - color = Color.BLUE - fuel = xpos = 0 - ypos = 0 57 End of lecture on 16 October 2006 58 Using our Car class Now we can use both our constructors: Car c1 = new Car(); Car c2 = new Car (Color.BLACK, 1, 2, 500); + Car() + Car (Color, int, int, int) + Car - color = Color.BLUE - fuel = xpos = 0 - ypos = 0 + Car() + Car (Color, int, int, int) + Car - color = Color.BLACK - fuel = xpos = 1 - ypos = 2 c1c2 59 So what does private mean? Consider the following code public class CarSimulation { public static void main (String[] args) { Car c = new Car(); System.out.println (c.fuel); } } Recall that fuel is a private instance variable in the Car class Private means that code outside the class CANNOT access the variable For either reading or writing Java will not compile the above code If fuel were public, the above code would work Note that its a different class! 60 So how do we get the fuel of a Car? Via accessor methods in the Car class: public int getFuel() { return fuel; } public Color getColor() { return color; } As these methods are within the Car class, they can read the private instance variables As the methods are public, anybody can call them public int getYPos() { return ypos; } public int getXPos() { return xpos; } 61 So how do we set the fuel of a Car? Via mutator methods in the Car class: public void setFuel (int f) { fuel = f; } public void setColor (Color c) { color = c; } As these methods are within the Car class, they can read the private instance variables As the methods are public, anybody can call them public void setXPos (int x) { xpos = x; } public void setYPos (int y) { ypos = y; } 62 Why use all this? These methods are called a get/set pair Used with private variables Well see why one uses these later in this slide set Our Car so far: + Car() + Car (Color, int, int, int) + void setXPos (int x) + void setYPos (int y) + void setColor (Color c) + void setFuel (int f) + int getFuel() + int getXPos() + int getYPos() + Color getColor() + Car - color = Color.BLUE - fuel = xpos = 0 - ypos = 0 63 Back to our specific constructor public class Car { private Color color = Color.BLUE; private int xpos = 0; private int ypos = 0; private int fuel = 1000; public Car (Color c, int x, int y, int f) { color = c; xpos = x; ypos = y; fuel = f; } } public class Car { private Color color = Color.BLUE; private int xpos = 0; private int ypos = 0; private int fuel = 1000; public Car (Color c, int x, int y, int f) { setColor (c); setXPos (x); setYPos (y); setFuel (f); } 64 Back to our specific constructor Using the mutator methods (i.e. the set methods) is the preferred way to modify instance variables in a constructor Well see why later 65 So whats left to add to our Car class? What else we should add: A mutator that sets both the x and y positions at the same time A means to use the Cars fuel A method to paint itself on the screen Lets do the first: public void setPos (int x, int y) { setXPos (x); setYPos (y); } Notice that it calls the mutator methods 66 Using the Cars fuel Whenever the Car moves, it should burn some of the fuel For each pixel it moves, it uses one unit of fuel We could make this more realistic, but this is simpler Math.abs() returns the absolute value public void setXPos (int x) { xpos = x; } public void setYPos (int y) { ypos = y; } public void setXPos (int x) { fuel -= Math.abs (getXPos()-x); xpos = x; } public void setYPos (int y) { fuel -= Math.abs (getYPos()-y); ypos = y; } 67 Setting both positions at once public void setPos (int x, int y) { setXPos(x); setYPos(y); } Notice that to access the instance variables, the accessor methods are used 68 Agricultural history Agricultural history Physics Physics Medicine Medicine Literature Literature Peace Peace Economics Economics Chemistry Chemistry Biology Biology Nutrition Nutrition Fluid dynamics Fluid dynamics The 2005 Ig Nobel Prizes The Significance of Mr. Richard Buckleys Exploding Trousers The pitch drop experiment, started in 1927 Neuticles artificial replacement testicles for dogs The 409 scams of Nigeria for a cast of rich characters Locust brain scans while they were watching Star Wars For an alarm clock that runs away, thus making people more productive Will Humans Swim Faster or Slower in Syrup? For cataloging the odors of 131 different stressed frogs To Dr. Yoshiro Nakamats who catalogued and analyzed every meal he ate for the last 34 years (and counting) Pressures Produced When Penguins Pooh Calculations on Avian Defaecation 69 Drawing the Car The simple way to have the Car draw itself: public void paint (Graphics g) { g.setColor (color); g.fillRect (xpos-50, ypos-100, 100, 200); } This draws a single rectangle that is 100 by 200 pixels in size Lets use constants for the cars height and width... 70 Drawing the Car A better version: private final int CAR_WIDTH = 100; private final int CAR_HEIGHT = 200; public void paint (Graphics g) { g.setColor (color); g.fillRect (getXPos()-CAR_WIDTH/2, getYPos()-CAR_HEIGHT/2, CAR_WIDTH, CAR_HEIGHT); } This makes it easier to change the car size We could have made the car size instance variables and set them via mutators Lets add tires! 71 Drawing the Car private final int CAR_WIDTH = 100; private final int CAR_HEIGHT = 200; private final int TIRE_WIDTH = 20; private final int TIRE_HEIGHT = 40; private final int TIRE_OFFSET = 20; public void paint (Graphics g) { g.setColor (color); g.fillRect (getXPos()-CAR_WIDTH/2, getYPos()-CAR_HEIGHT/2, CAR_WIDTH, CAR_HEIGHT); // Draw the tires g.setColor (Color.BLACK); g.fillRect (getXPos()-(CAR_WIDTH/2+TIRE_WIDTH), getYPos()-(CAR_HEIGHT/2-TIRE_OFFSET), TIRE_WIDTH, TIRE_HEIGHT); g.fillRect (getXPos()-(CAR_WIDTH/2+TIRE_WIDTH), getYPos()+(CAR_HEIGHT/2-TIRE_OFFSET-TIRE_HEIGHT), TIRE_WIDTH, TIRE_HEIGHT); g.fillRect (getXPos()+(CAR_WIDTH/2), getYPos()+(CAR_HEIGHT/2-TIRE_OFFSET-TIRE_HEIGHT), TIRE_WIDTH, TIRE_HEIGHT); g.fillRect (getXPos()+(CAR_WIDTH/2), getYPos()-(CAR_HEIGHT/2-TIRE_OFFSET), TIRE_WIDTH, TIRE_HEIGHT); } Dont worry about this just know that it draws four tires 72 What happens when the car runs out of fuel? We could do a number of things: Not allow the car to move anymore Print out a message saying, fill me up! Well color the car red Well insert the following code at the beginning of the paint() method: if ( fuel < 0 ) { color = Color.RED; } 73 Drawing the Car private final int CAR_WIDTH = 100; private final int CAR_HEIGHT = 200; private final int TIRE_WIDTH = 20; private final int TIRE_HEIGHT = 40; private final int TIRE_OFFSET = 20; public void paint (Graphics g) { if ( fuel < 0 ) { color = Color.RED; } g.setColor (color); g.fillRect (getXPos()-CAR_WIDTH/2, getYPos()-CAR_HEIGHT/2, CAR_WIDTH, CAR_HEIGHT); // Draw the tires g.setColor (Color.BLACK); g.fillRect (getXPos()-(CAR_WIDTH/2+TIRE_WIDTH), getYPos()-(CAR_HEIGHT/2-TIRE_OFFSET), TIRE_WIDTH, TIRE_HEIGHT); g.fillRect (getXPos()-(CAR_WIDTH/2+TIRE_WIDTH), getYPos()+(CAR_HEIGHT/2-TIRE_OFFSET-TIRE_HEIGHT), TIRE_WIDTH, TIRE_HEIGHT); g.fillRect (getXPos()+(CAR_WIDTH/2), getYPos()+(CAR_HEIGHT/2-TIRE_OFFSET-TIRE_HEIGHT), TIRE_WIDTH, TIRE_HEIGHT); g.fillRect (getXPos()+(CAR_WIDTH/2), getYPos()-(CAR_HEIGHT/2-TIRE_OFFSET), TIRE_WIDTH, TIRE_HEIGHT); } 74 Our car in action CarGUI.java CarGUI.java 75 How well do you feel you understand the Car class? a) Very well! This stuff is so easy. b) With a little review, Ill be good. c) Not very well at all. d) Im so lost. Whats a car again? e) Id rather not answer this question, thanks. 76 Fan-supplied demotivators! 77 Parameter passing 78 Modifying parameters Consider the following code public class Methods5 { public static void changeValue (int x) { x = 7; } public static void main (String args[]) { int y = 5; changeValue(y); System.out.println (y); } } What gets printed? 5 is printed 5 y 5 x 7 x 79 Program Demo Methods5.java Methods5.java 80 Pass by value Java is a pass-by-value language This means that a COPY of the parameters value is passed into the method If a method changes that value, only the COPY is changed Once the method returns, the copy is forgotten And thus the change is not visible outside the method There are other manners of returning values that are used in other languages Pass by reference Pass by name (nobody uses this anymore) We will see about trying to change object parameters later in this slide set 81 Modifying parameters Consider the following code import java.awt.*; public class Methods6 { public static void changeValue (Rectangle r) { r.setSize (10,20); } public static void main (String args[]) { Rectangle rect = new Rectangle(1, 2); changeValue(rect); System.out.println (rect.getWidth()); } } What gets printed? 10 is printed + Rectangle () + Rectangle (int width, int height) + setSize (int width, int height) + getWidth () Rectangle - width = 1 - height = 2 rect + Rectangle () + Rectangle (int width, int height) + setSize (int width, int height) + getWidth () Rectangle - width = 10 - height = 20 r 82 Program Demo Methods6.java Methods6.java 83 Pass by value Java is still a pass-by-value language This means that a COPY of the parameters value is passed into the method But the parameter is a REFERENCE to an object The object itself is not passed So any changes to the reference are forgotten about But you can modify the object it refers to 84 Modifying parameters Consider the following code import java.awt.*; public class Methods7 { public static void changeValue (Rectangle r) { r = new Rectangle (10,20); } public static void main (String args[]) { Rectangle rect = new Rectangle(1, 2); changeValue(rect); System.out.println (rect.getWidth()); } } What gets printed? 1 is printed + Rectangle () + Rectangle (int width, int height) + setSize (int width, int height) + getWidth() Rectangle - width = 1 - height = 2 rect + Rectangle () + Rectangle (int width, int height) + setSize (int width, int height) + getWidth() Rectangle - width = 10 - height = 20 r The only change! 85 Program Demo Methods7.java Methods7.java 86 Pass by value Java is still a pass-by-value language This means that a COPY of the parameters value is passed into the method But the parameter is a REFERENCE to an object The object itself is not passed So any changes to the reference are forgotten about But you can modify the object it refers to 87 How well do you feel you understand parameter passing? a) Very well! This stuff is so easy. b) With a little review, Ill be good. c) Not very well at all. d) Im so lost. Whats a parameter again? e) Id rather not answer this question, thanks. 88 Yale vs. Harvard 89 End of lecture on 18 October 2006 90 Miscellaneous Stuff 91 What Im not expecting you to know yet What the static keyword means And why the main() method is And why other methods are not Why you should always call the mutator methods, instead of setting the field directly Just know that its a good programming practice, and follow it Well see why later Why instance variables are supposed to be private Just know that its a good programming practice, and follow it Again, well see why soon 92 Terminology An attribute of a class can be called: Instance variable or class variable Well see the difference later Static variable (or static field) Synonymous with class variable Field Generally means either type Variable Also means either type Attribute Property Argh! I will generally use the terms variable or field when I am not differentiating between the two And instance variable/field and class variable/field when I am 93 The main() method Consider a class with many methods: public class WhereToStart { public static void foo (int x) { //... } public static void bar () { //... } public static void main (String[] args) { //... } } Where does Java start executing the program? Always at the beginning of the main() method! 94 Running a class without a main() method Consider the Car class It had no main() method! The main() method was in the CarSimulation (or CarGUI) class So lets try running it 95 Program Demo Car.java Car.java 96 Variable initialization A local variable is NOT initialized to a default value This is any variable declared within a method Or within a block within a method This is pretty stupid, in my opinion Parameters are initialized to whatever value they are passed Instance and class variables are initialized to default values Numbers to zero, booleans to false, references to null This means any field in a class Either class variables or instance variables 97 How well do you feel you understand creating classes so far? a) Very well! This stuff is so easy. b) With a little review, Ill be good. c) Not very well at all. d) Im so lost. Whats a class again? e) Id rather not answer this question, thanks. 98 Todays demotivators 99 End of lecture on 23 October 2006 Re-did the parameter passing slides using the Frisbee demo And did two sets of Jeopardy review 100 The Circle class Introducing static-ness, visibilities, etc. 101 A Circle class We are going to develop a Circle class Perhaps for use in a graphics program Why? Partly to review creating classes Go over some topics that were a bit fuzzy Constructors and creating objects Show why one uses the get/set methods instead of directly modifying the instance variables Discuss visibilities (public, private, etc.) Discuss the static keyword 102 Circle class properties What properties does a circle have? Radius PI = Color (if plotting in a graphics program) (x,y) location These properties will become instance variables We are only going to play with the first two (radius and PI) in this example Thus, we are ignoring the color and location 103 Our Circle class Circle c = new Circle(); public class Circle { double radius; double PI = ; } Note the fields are not static Note the radius field is not initialized by us Were ignoring the public for now c Circle - radius = PI = - + 104 Accessing our Circle object Any variable or method in an object can be accessed by using a period The period means follow the reference Example: System.in Example: System.out.println (c.radius); Example: c.PI = 4; This is bad PI should have been declared final (this will be done later) c Circle - radius = PI = - + 105 Whats the output? public class Circle { double radius; double PI = ; } public class CircleTest { public static void main (String[] args) { int x; Circle c = new Circle(); System.out.println (x); } } When a variable is declared as part of a method, Java does not initialize it to a default value Java will give a variable not initialized error 106 Whats the output now? public class Circle { double radius; double PI = ; } public class CircleTest { public static void main (String[] args) { int x; Circle c = new Circle(); System.out.println (c.radius); } } When a variable is declared as part of a class, Java does initialize it to a default value Java outputs 0.0! 107 Whats going on? A (method) variable needs to be initialized before it is used Usually called a local variable A instance variable is automatically initialized by Java All numbers are initialized to 0, booleans to false, etc. This is a bit counter-intuitive 108 Circle class behaviors What do we want to do with (and to) our Circle class? Create circles Modify circles (mutators) Find out about our circles properties (accessors) Find the area of the circle Plot it on the screen (or printer) A few others These will be implemented as methods 109 Calling the Circle constructor To create a Circle object: Circle c1 = new Circle(); This does four things: Creates the c1 reference Creates the Circle object Makes the c1 reference point to the Circle object Calls the constructor with no parameters (the default constructor) The constructor is always the first method called when creating (or constructing) an object c1 Circle - radius = PI = - + Circle() + Circle (double r) + 110 Calling the Circle constructor To create a Circle object: Circle c1 = new Circle(2.0); This does four things: Creates the c1 reference Creates the Circle object Makes the c1 reference point to the Circle object Calls the constructor with 1 double parameters (the specific constructor) The constructor is always the first method called when creating (or constructing) an object c1 Circle - radius = PI = - + Circle() + Circle (double r) + 111 Constructors Remember, the purpose of the constructor is to initialize the instance variables PI is already set, so only radius needs setting public Circle() { radius = 1.0; } public Circle (double r) { radius = r; } Note there is no return type for constructors Note that the constructor name is the EXACT same as the class name Note that there are two methods with the same name! 112 What happens in memory Consider: Circle c = new Circle(); A double takes up 8 bytes in memory Thus, a Circle object takes up 16 bytes of memory As it contains two doubles c Circle - radius = PI = + Circle() + Circle (double r) + Circle - radius = PI = c Shorthand representation 113 Circle class: our class so far public class Circle { double radius; double PI = ; public Circle() { radius = 1.0; } public Circle (double r) { radius = r; } 114 How well do you feel you understand the Constructors? a) Very well! This stuff is so easy. b) With a little review, Ill be good. c) Not very well at all. d) Im so lost. Whats a class again? e) Id rather not answer this question, thanks. 115 What do these pictures mean? Light beer Light beer Dandy lions Dandy lions Assaulted peanut Assaulted peanut Eggplant Eggplant Dr. Pepper Dr. Pepper Pool table Pool table Tap dancers Tap dancers Card shark Card shark King of pop King of pop I Pod I Pod Gator aide Gator aide Knight mare Knight mare Hole milk Hole milk 116 Circle class: our class so far public class Circle { double radius; double PI = ; public Circle() { radius = 1.0; } public Circle (double r) { radius = r; } 117 Consider the following code public class CircleTest { public static void main (String[] args) { Circle c1 = new Circle(); Circle c2 = new Circle(); Circle c3 = new Circle(); Circle c4 = new Circle(); } } 118 What happens in memory There are 4 Circle objects in memory Taking up a total of 4*16 = 64 bytes of memory Circle - radius = PI = c1 Circle - radius = PI = c2 Circle - radius = PI = c3 Circle - radius = PI = c4 119 Consider the following code public class CircleTest { public static void main (String[] args) { Circle c1 = new Circle(); //... Circle c = new Circle(); } } public class CircleTest { public static void main (String[] args) { Vector v = new Vector(); for ( int i = 0; i < ; i++ ) v.add (new Circle()); } } These programs create 1 million Circle objects! 120 What happens in memory There are 1 million Circle objects in memory Taking up a total of 1,000,000*16 16 Mb of memory Note that the final PI field is repeated 1 million times Circle - radius = PI = c1 Circle - radius = PI = c2 Circle - radius = PI = c 121 Total memory usage: 8 Mb + 8 bytes (1,000,000+1=1,000,001 doubles) The use of static for fields If a variable is static, then there is only ONE of that variable for ALL the objects That variable is shared by all the objects Total memory usage: 16 bytes (1+1=2 doubles) Total memory usage: 40 bytes (4+1=5 doubles) Circle - radius = 1.0 c1 Circle - radius = 1.0 c2 c Circle - radius = 1.0 c3 c4 Circle - radius = 1.0 PI 122 More on static fields What does the following print Note that PI is not final Circle c1 = new Circle(); Circle c2 = new Circle(); Circle c3 = new Circle(); Circle c4 = new Circle(); c1.PI = 4.3; System.out.println (c2.PI); It prints 4.3 Note you can refer to static fields by object.variable 123 Even more on static fields There is only one copy of a static field no matter how many objects are declared in memory Even if there are zero objects declared! The one field is common to all the objects Static variables are called class variables As there is one such variable for all the objects of the class Whereas non-static variables are called instance variables Thus, you can refer to a static field by using the class name: Circle.PI 124 Even even more on static fields This program also prints 4.3: Circle c1 = new Circle(); Circle c2 = new Circle(); Circle c3 = new Circle(); Circle c4 = new Circle(); Circle.PI = 4.3; System.out.println (c2.PI); 125 Even even even more on static fields Weve seen static fields used with their class names: System.in(type: InputStream) System.out(type: OutputStream) Math.PI(type: double) Integer.MAX_VALUE(type: int) Game.BOARD_X_COORD(in HW J6) 126 How well do you feel you understand static-ness? a) Very well! This stuff is so easy. b) With a little review, Ill be good. c) Not very well at all. d) Im so lost. Whats a class again? e) Id rather not answer this question, thanks. 127 New 2005 demotivatiors! 128 Back to our Circle class public class Circle { double radius; final static double PI = ; public Circle() { radius = 1.0; } public Circle (double r) { radius = r; } } But it doesnt do much! Note that PI is now final and static 129 Adding a method public class Circle { double radius; final static double PI = ; // Constructors... double computeArea () { return PI*radius*radius; } Note that a (non-static) method can use both instance and class variables 130 Using that method public class CircleTest { public static void main (String[] args) { Circle c = new Circle(); c.radius = 2.0; double area = c.computeArea(); System.out.println (area); } } Prints 131 Circle - radius = PI = - + Circle() + Circle (double r) + computeArea() + What happens when that method is called public class Circle { double radius; final static double PI = ; public Circle() { radius = 1.0; } // other constructor double computeArea () { return PI*radius*radius; } } public class CircleTest { public static void main (String[] args) { Circle c = new Circle(); c.radius = 2.0; double area = c.computeArea(); System.out.println (area); } } c Circle - radius = PI = - + Circle() + Circle (double r) + computeArea() + area Circle - radius = PI = - + Circle() + Circle (double r) + computeArea() + 132 Review of our Circle class public class Circle { double radius; final static double PI = ; public Circle() { } public Circle (double r) { radius = r; } double computeArea () { return PI*radius*radius; } Slight change from before 133 A note about methods/variable order Within a method, a variable must be declared before it is used In a class, methods and variables can be declared in any order This is different than C++ 134 Adding another method double oneOverRadius() { return 1.0/radius; } I couldnt think of a good reason to divide something by the radius 135 What happens now? Code in class CircleTests main() method Circle c = new Circle(); // c.radius is now 0.0 System.out.println (c.oneOverRadius()); Java wont crash, but many other programming languages (C and C++, in particular) will So well call this a crash for the sake of this lecture Java prints Infinity Not what we wanted, though! 136 One way to fix this public class Circle { double radius = 1.0; final static double PI = ; // Constructors... double computeArea () { return PI*radius*radius; } double oneOverRadius() { return 1.0/radius; } Note that the radius variable is now initialized to 1.0 137 Back to our program This code will now run properly: Circle c = new Circle(); // c.radius = 1.0 System.out.println (c.oneOverRadius()); But this code will crash: Circle c = new Circle(); // c.radius = 1.0 c.radius = 0.0; System.out.println (c.oneOverRadius()); 138 Where the crash occurs public class CircleTest { public static void main (String[] args) { Circle c = new Circle(); // c.radius = 1.0 c.radius = 0.0; System.out.println (c.oneOverRadius()); } public class Circle { double radius = 1.0; final static double PI = ; double computeArea () { return PI*radius*radius; } double oneOverRadius() { return 1.0/radius; } Here is the badly written code Here is where the crash occurs 139 Motivation for private fields Problem: We do not want people using our Circle class to be able to modify the fields on their own Solution: Dont allow other code to modify the radius field Give it private visibility private means that only code within the class can modify the field 140 One way to fix this public class Circle { private double radius = 1.0; final static double PI = ; // Constructors... double computeArea () { return PI*radius*radius; } double oneOverRadius() { return 1.0/radius; } Note that the radius variable is now private 141 From Dubai 142 Back to our program This code will now not compile: Circle c = new Circle(); // c.radius = 1.0 c.radius = 0.0; System.out.println (c.oneOverRadius()); Java will give a compile-time error: radius has private access in Circle 143 Back to our program This code will also not compile: Circle c = new Circle(); // c.radius = 1.0 System.out.println (c.radius); Java will give the same compile-time error: radius has private access in Circle 144 The problem now But now you cant modify a Circles radius! Or find out what it is Solution: Use a get/set methods in Circle: A mutator method: void setRadius (double r) { radius = r; } An accessor method: double getRadius () { return radius; } 145 Our Circle class so far public class Circle { private double radius = 1.0; final static double PI = ; // Constructors... double computeArea () { return PI*radius*radius; } double oneOverRadius() { return 1.0/radius; } void setRadius (double r) { radius = r; } double getRadius () { return radius; } 146 Using the get/set methods public class CircleTest { public static void main (String[] args) { Circle c = new Circle(); c.setRadius (1.0); System.out.println (c.computeArea()); System.out.println (c.getRadius()); } public class Circle { private double radius = 1.0; final static double PI = ; double computeArea () { return PI*radius*radius; } double oneOverRadius() { return 1.0/radius; } void setRadius (double r) { radius = r; } double getRadius () { return radius; } Here a method is invoked Here the change to radius occurs 147 Wait! Another problem! public class CircleTest { public static void main (String[] args) { Circle c = new Circle(); c.setRadius (0.0); System.out.println (c.oneOverRadius()); } } Here is the problem now 148 This problem is easily fixed Change the setRadius() method to the following void setRadius (double r) { if ( r > 0.0 ) radius = r; else radius = 1.0; } Now there is (almost) no way for code outside the Circle class to change the radius to zero This is the purpose of mutators To prevent changing the fields to a bad value Well see another motivation in a bit 149 End of lecture on 30 Oct 2006 Also went over the second midterm and HW J6 150 Total memory usage: 8 Mb + 8 bytes (1,000,000+1=1,000,001 doubles) Review of static for fields If a variable is static, then there is only ONE of that variable for ALL the objects That variable is shared by all the objects Total memory usage: 16 bytes (1+1=2 doubles) Total memory usage: 40 bytes (4+1=5 doubles) Circle - radius = 1.0 c1 Circle - radius = 1.0 c2 c Circle - radius = 1.0 c3 c4 Circle - radius = 1.0 PI 151 Visibilities in Java There are four visibilities: private : Only code within the same class can access the field or method Note: access means reading or writing the field, or invoking the method public : Any code, anywhere, can access the field or method protected : Used with inheritance We wont get to that this semester default : Almost the same as public This is the default (duh!) Note that it cant be specified like the others Also called package 152 A few notes on visibilities You can NOT specify visibilities for method variables Any method variable can only be accessed within that method Think of it as public within the method (after its defined) and private outside the method You can also specify visibilities for methods and classes We will see this a bit in this course 153 How well do you feel you understand visibilities? a) Very well! This stuff is so easy. b) With a little review, Ill be good. c) Not very well at all. d) Im so lost. Whats a class again? e) Id rather not answer this question, thanks. 154 Overriding methods (and constructors) Consider the following code: Circle c1 = new Circle (); Circle c2 = new Circle (2.0); Java knows which constructor to call by the list of parameters This is called overloading Meaning it means multiple things, depending on the context Weve seen overloading before: 3+4Performs integer addition Performs floating-point addition 3+4Performs string concatenation The + operator is overloaded Creates a Circle of radius 1.0 Creates a Circle of radius 2.0 155 Overriding methods (and constructors), take 2 The following Circle constructors would not be allowed: We are assuming PI is not final for this example public Circle() { radius = 1.0; } public Circle (double r) { radius = r; } public Circle (double p) { PI = p; } When Circle(1.0) is called, which one is meant? 156 Using mutators in the constructor Our second constructor has a problem: public Circle (double r) { radius = r; } Consider the following code: Circle c = new Circle (0.0); System.out.println (c.oneOverRadius()); The method is dividing by zero (again) 157 Using mutators in the constructor This is easily fixed! Our revised constructors: public Circle() { setRadius (1.0); } public Circle (double r) { setRadius (r); } The mutator will properly set the radius (and wont set it to zero) 158 Chapter 2: Computer bugs 159 Why we always use the mutators Consider a modified version of our circle class: class Circle { double radius; double diameter; String size; //... Our mutator now looks like this: Thats a lot of code to copy if you decide not to call the mutator! void setRadius (double r) { if ( radius