2.08k likes | 2.11k Views
Learn about defining and using methods in Java. Understand the basics of object-oriented programming while creating and manipulating objects with specific attributes and behaviors. Develop foundational skills for efficient problem-solving.
E N D
Classes Chapter 4 Fall 2006 CS 101 Aaron Bloomfield
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
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
Known Classes • Classes we’ve seen • BigInteger • String • Rectangle • Vector • Scanner • System • Classes we’ll be seeing soon • BigDecimal • But the first step is on creating methods…
Methods we’ve seen • We’ve 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
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(); } }
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); }
Program Demo • Methods1.java
stdin 1 value Scanner What’s happening there 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(); // ... }
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, I’ll 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
A revised HW 3 flowchart Green paths are “yes” paths, red are “no” paths We’ll make a slight modification to the diagram: Note that this part is repeated twice! Start over Revamping HW J3 Cynical guru Start here Done tech support? Bitter yet? Successful managing? Promoted Become a coder Been a sysadmin? Hate people? Worked with NT? Start over Public danger Want to play w/nukes? Defense contractor
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); 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 doBottomPartOfFlowchart(); } else doBottomPartOfFlowchart(); HW J3 Code with methods
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); }
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.
Pros of Refactoring • Benefits of Refactoring • Reduce length of code • As you don’t 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 what’s 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
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)
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 (we’ll 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
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 don’t return a value • System.out.println(), for example
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); } }
Program Demo • Methods2.java
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
How well do you feel you understand return values? • Very well! This stuff is so easy. • With a little review, I’ll be good. • Not very well at all. • I’m so lost. What’s a return type again? • I’d rather not answer this question, thanks.
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) x2, x3, and x4
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); }
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; }
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)); } }
Program Demo • Methods3.java
The 2006 Ig Nobel Prizes • Ornithology • Nutrition • Peace • Acoustics • Mathematics • Literature • Medicine • Physics • Chemistry • Biology For explaining why woodpeckers don’t 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 don’t 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
name String courseName “CS 101” 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); } }
Program Demo • Methods4.java
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?
Program Demo • Methods5.java
Pass by value • Java is a pass-by-value language • This means that a COPY of the parameter’s 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
How well do you feel you understand parameters? • Very well! This stuff is so easy. • With a little review, I’ll be good. • Not very well at all. • I’m so lost. What’s a return type again? • I’d rather not answer this question, thanks.
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 variable is visible anywhere in the Scoping class This parameter is visible only in the foo() method This local variable is visible until the end of the main() method
Method notes summary • You can put the methods in a class in any order • Java doesn’t 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 it’s void, then no value is returned • Parameters can’t be changed within a method • Although the objects that the parameters point to can be
How well do you feel you understand scoping? • Very well! This stuff is so easy. • With a little review, I’ll be good. • Not very well at all. • I’m so lost. What’s a return type again? • I’d rather not answer this question, thanks.
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; //... }
Car - color - xpos - fuel - ypos + … Car’s instance variables public class Car { private Color color; private int xpos; private int ypos; private int fuel; //... }
Car - color = null - xpos = 0 - fuel = 0 - ypos = 0 + … 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 behaviors or methods • What can a car do? And what can you do to a car? • Move it • Change it’s x and y positions • Change it’s 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
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; }