Download presentation
Presentation is loading. Please wait.
Published bySteven Benson Modified over 9 years ago
1
Methods Material from Chapters 5 & 6
2
Review of Chapters 5 to 7 Methods »(AKA subroutines, functions, procedures) understand method calls create a class of related methods define and call methods from helper class create and use class constants create a class to hold and manipulate data create and call methods that take/return arrays
3
Using Methods We’ve been using methods from the start print and println are methods (as is printf) nextInt, nextDouble, next, and nextLine, too equals, equalsIgnoreCase, startsWith, and all those other things we can ask a String to do pow, sqrt, max, min, and all those other things we can ask Math to do
4
Why Do We Have Methods? Code Re-use Doing “same” thing in multiple places » we do a lot of printing! Code Hiding (Encapsulation) Secret Implementation independence Code Abstraction Top-down design
5
Parts of a Method Call All method calls are alike: Math.pow(5, 7) kbd.nextInt() resp.equalsIgnoreCase(“yes”) Someone.doSomething(with, these) »Someone (Math, kbd, resp, …) »doSomething (pow, nextInt, equalsIgnoreCase, …) »(with, these) ((5, 7), (), (“yes”))
6
Someone? Can ask a class or an object class name starts with a capital letter (Math) object name starts with a little letter (kbd) Objects are variables with a class data type Scanner kbd = new Scanner(System.in); String resp = kbd.nextLine(); Methods are declared in that class class Math, class Scanner, class String, …
7
doSomething? Name of the method says what it does… print, println, … »Verb phrase in the imperative (do, be) …or what it gives us… length, nextInt, nextLine, … »Noun phrase …or what it tells us equals, equalsIgnoreCase, startsWith »Verb phrase in the declarative (does, is)
8
With These? Method needs more information “Arguments” are given to the method »we also say that the method takes arguments Math.pow(5, 7) – 5 and 7 are both arguments resp.startsWith(“y”) – “y” is the (one) argument Some methods take no arguments kbd.nextLine() – needs no more information
9
Void Methods Some methods are complete commands in themselves telling the computer to do something System.out.println(“A complete command”); These methods cannot be used as part of a command String resp = System.out.println(“What???”);
10
Return Values Some methods return values Math.sqrt(x) returns the square root of x kbd.nextInt() returns the next (int) value These (usually) used as part of a command int n = kbd.nextInt(); double y = Math.sqrt(n); if (resp.startsWith(s)) { But may be used alone sometimes kbd.nextLine(); // we don’t care what the line was!
11
“Chaining” Method Calls When one method returns an object value… e.g. resp.toUpperCase() if resp is “yes”, resp.toUpperCase() is “YES” …we can ask that object a question e.g. resp.toUpperCase().startsWith(“Y”) resp is “yes” (which doesn’t start with “Y”) resp.toUpperCase() is “YES” “YES” does start with “Y”
12
The Job of the Method Every method has a job to do print a line, get the next int, … Call the method the job gets done that’s what the method is there for How the method does the job… the body/definition of the method …is just details! caller (“client”) just wants it done
13
Classes Combine Methods Classes collect related methods together Math collects math functions together String collects methods that work with Strings Scanner collects methods for scanning input We can make our own classes Converter has methods converting measures Utilities has methods for printing out titles and paragraphs
14
Example Class: Converter A class for objects that know how to convert between metric and imperial/US measurements use it like this: double degF = Converter.fahrenheitFromCelsius(29.0); System.out.println(“29C = ” + degF + “F”); double hgtInCM = Converter.cmFromFeetInches(5, 8); System.out.println(“5’ 8\” = ” + hgtInCM + “cm”);
15
Declaring Classes and Methods Need to declare the class (just like before) public class Converter {... // methods in here //... // methods in here //} Need to declare the methods (like before) public static...... (...) {.... // commands in here //.... // commands in here //} Compare: public static void main(String[] args) {... }
16
The Method Header / Interface First line of the method definition public static double cmFromFeetInches(double ft, double in) public – this method can be called static – this method belongs to the class »not to an object double – the return type cmFromFeetInches – the name of the method (double ft, double in) – the parameter list
17
Arguments vs. Parameters Arguments are values (10, 15.4, “Hello”) Parameters are variables need to be declared like variables »(double degC), (int ft, double in) only differences are: »declarations are separated by commas, not ;s »every parameter needs its own type, even if they’re all the same type: (double x, double y, double z), (int a, int b)(double x, double y, double z), (int a, int b)
18
Method Body Commands for the method go in its body the part between the braces { … } Can use anything we use in main »create variables (including a Scanner, BUT DON’T) »input & output »loops & conditionals »call other functions (yup!) »other stuff we haven’t even learned about yet plus we can use a “return” command
19
Method “Stubs” A stub is a very small method that compiles but doesn’t work properly Methods that say they will return a value need to return a value! so they need a return command just add return command with suitable value public static double cmFromFeetInches(int ft, double in) { return 0.0; return 0.0;}
20
Value-Returning Method Body Calculate the value that needs to be returned Then return it public double cmFromFeetInches(int ft, double in) { double result = (12 * ft + in) * 2.54; return result; } Or combine the two into one step! public double cmFromFeetInches(int ft, double in) { return (12 * ft + in) * 2.54; }
21
Class Constants Shouldn’t use “magic numbers” un-named numbers that mean something 12 is the number of inches in a foot 2.54 is the number of cm in an inch Declare these as constants public class Converter { public static final int IN_PER_FT = 12; public static final double CM_PER_IN = 2.54; final = never going to change
22
Method Comments Javadoc comment (/** … */) brief statement of the method purpose @param for each parameter (if any) @return if it’s a value-returning method /** * Converts distance from feet and inches to centimetres. * Converts distance from feet and inches to centimetres. * * @param ft (whole) number of feet in the distance * @param ft (whole) number of feet in the distance * @param in number of (extra) inches in the distance * @param in number of (extra) inches in the distance * @return same distance, but measured in centimetres * @return same distance, but measured in centimetres */ */
23
Local Variables The parameters and any variables you create inside the method body are “local” it only makes sense to use them in the method cannot be used outside the method »in particular, not in main! They are, in fact, temporary variables they only exist while the method is running »not before; not after. »created anew every time the method is called
24
Input & Output Value-returning methods usually do NONE common mistake is to have it ask for the value to use – but we already gave it that value fahrenheitFromCelsius(29.0) common mistake is to have it print the answer – but what if main doesn’t want it printed? // get degrees in F so we know if user guesses right tempInF = fahrenheitFromCelsius(29.0); just do the math; leave caller to do the I/O
25
Utilities Methods A class with helpful printing methods use it like this: Utilities.printTitle(“Utilities Demo”); Utilities.printParagraph(“This program demonstrates ” + “the Utilities class.”); Utilities.printParagraph(“This paragraph was produced ” + “by the printParagraph method.”); Utilities.printParagraph(“This paragraph’s much longer ” + “than the one above, and needs to be \“wrapped\” ” + “on the output line. The method does that for us!”);
26
Utilities Methods printTitle print underlined, with blank lines printParagraph wrap words, add blank line Utilities Demo -------------- This program demonstrates the Utilities class. This paragraph was produced by the printParagraph method. This paragraph’s much longer than the one above and needs to be “wrapped” on the output line. The method does that for us!
27
Utilities Class Stubs Replace return type with “void” void = empty – nothing to be returned don’t even need a return command! public class Utilities{ public static void printTitle(String title) { } public static void printParagraph(String text) { }}
28
printTitle Body public static void printTitle(String title) { System.out.print("\n" + title + "\n"); System.out.print("\n" + title + "\n"); for (int i = 1; i <= title.length(); i++) for (int i = 1; i <= title.length(); i++) System.out.print('-'); System.out.print('-'); System.out.print("\n\n"); System.out.print("\n\n");} print blank line and title; end title line for each letter in the title »print a hyphen (to underline that letter) end underline line, print blank line
29
Arrays as Parameters Methods can have [] parameters just declare the parameter to be an array! public static int sumArray(int[] arr) It’s just like any other parameter gets its value from the method call It’s just like any other array it knows how long it is
30
Method to Sum an Array Array comes from caller int[] n = new int[]{2, 3, 5, 7, 11}; int addedUp = ArrayOperations.sum(n); Method adds up its elements public static int sum(int[] a) { int sum = 0; int sum = 0; for (int i = 0; i < a.length; i++) { for (int i = 0; i < a.length; i++) { sum += a[i]; sum += a[i]; } return sum; return sum;} TestArrayOperations.java ArrayOperations.java
31
Returning Arrays Methods can return arrays int[] c = ArrayOperations.add(a, b); return type is an array type public static int[] add(int[] a, int[] b) May need to create the array to be returned int len = Math.min(a.length, b.length); int[] result = new int[len]; … return result;
32
Classes vs. Objects Classes can be used right away Utilities.printTitle(“Utilities Demo”); »so long as we can “see” them Objects need to be created »except for Strings, which are so massively useful… Scanner kbd = new Scanner(System.in); objects contain data different objects have different data methods are mostly about that data
33
Object Oriented Programming Programming arranged around objects main program creates the objects objects hold the data objects call each others’ methods objects interact to achieve program goal Very important in GUI programs Graphical User Interface »WIMP (Windows, Icons, Menus, Pointers) interface
34
What are Objects? An object in a program often represents a real-world object… an animal, a vehicle, a person, a university, … …or some abstract object… a colour, a shape, a species, … …or some thing the program needs to track a string, a window, a GUI button, …
35
Object Classes What kind of object it is its data type is a Class String s1, s2;// s1 & s2 are Strings Scanner kbd, str;// kbd & str are Scanners Animal rover, hammy;// rover & hammy are Animals Color c1, c2;// c1 & c2 are Colors JButton okButton, cancelButton;// … are JButtons Objects in the same class do the same kinds of things To use Color & JButton, you need to import java.awt.Color; import javax.swing.JButton;
36
Declaring Objects Most Java objects created using new »usually with arguments »arguments depend on the class kbd = new Scanner(System.in); rover = new Animal(Animal.DOG);// I made this up! c1 = new Color(255, 127, 0);// This is orange okButton = new JButton(“OK”); »not Strings, tho’ s1 = “Strings are special!”; s2 = new String(“But this works, too!”); Remember to import java.awt.Color; import javax.swing.JButton;
37
Object Data and Methods Each kind of object has its own kind of data String has array of characters Color has red, green, and blue components Methods access that data get pieces of it, answer questions about it, change it name characters Mark Young orange red green blue 255 127 0
38
A Student Class A class for holding student information student number name home address grades ... We’ll start simple: number, name, one grade (in percent) »these are called “properties” of the Student stu number name pctGrade A00123456 “Dent, Stu” 81
39
Instance Variables public class Student { private String aNumber;// A00... private String name;// family name, givens private int pctGrade;// 0..100 …} instance variables are declared private (not public) no “static”; no “final” methods will be declared below
40
Public vs. Private Public = anyone can use these Public name anyone can change my name Public grade anyone can change my grade Public method anyone can use this method Private = only I can use them Private name only I can change my name Private grade only I can change my grade Anyone can ask, but I get a veto Actually, any Student can change my name/grade; other classes have to ask
41
Static vs. Non-Static Static = shared with all others of my kind Static name all students have the same name Static grade all students have the same grade Static method all students give same answer Non-Static = each object has its own Non-static name each student has own name Non-static grade each student has own grade
42
Declaring a Student Give A#, name and grade when create Student s1, s2; s1 = new Student(“A00123456”, “Dent, Stu”, 81); s2 = new Student(“A00234567”, “Tudiaunt, A.”, 78); or can combine the steps: Student s3 = new Student(“A00111111”, “No, Dan”, 0); arguments are String (aNumber), String (name), and int (percent grade)
43
Student Constructor Constructor “builds” the Student object gives a value to each of the instance variables private String aNumber;// A00… private String name;// Last, First private int grade;// 0.. 100 public Student(String a, String n, int g) { aNumber = a; aNumber = a; name = n; name = n; grade = g; grade = g;} a, n, and g are the parameters: the values the caller wants to use; aNumber, name, and grade are the instance variables: the values we will use.
44
Constructors Generally declared public anyone can build a Scanner, a Student, … Name is exactly the same as the class name class Student constructor named “Student” class Animal constructor named “Animal” No return type not even void! Argument for each instance variable (often)
45
Constructors Their job is to give a value to each instance variable in the class and so often just a list of assignment commands »instanceVariable = parameter; aNumber = a; name = n; grade = g; But may want to check if values make sense so maybe a list of if-else controls
46
Checking Values If given value makes no sense, use a default »but still instanceVariable = (something); public Student(String a, String n, int g) { if (a.startsWith(“A”) && a.length() == 9) { if (a.startsWith(“A”) && a.length() == 9) { aNumber = a; aNumber = a; } else { } else { aNumber = “(illegal)”; aNumber = “(illegal)”; } name = n; name = n; …}
47
Methods to Get Information Instance variables are private client can’t use them! System.out.println(stu.name); “Getters” usually named get + name of instance variable »but capitalized in camelCase System.out.println(stu.getName());System.out.println(stu.getANumber());System.out.println(stu.getPctGrade()); name is private in Student!
48
Student “Getters” Getters are very simple! just return the instance variable »method return type same as type of variable private String aNumber;// A00… private String name;// Last, First public String getName() { return name; return name;} public String getANumber() { return aNumber; return aNumber;} public! Anyone can ask! No static! Each student has own name!
49
Methods to Change Information Some fields may need to be changed name and grade, for example student number should NOT be changed! Need a method to do that, too! stu.name = “Dummikins, Dummy”; Methods called “setters” named “set” + name of instance variable stu.setName(“Dummikins, Dummy”); stu.setPctGrade(1000000); name is private in Student!
50
Setters Given the new value the caller wants normally we will use that value public static void setName(String newName) { name = newName; name = newName;} but we might want to reject it public static void setPctGrade(int newGrade) { if (0 <= grade && grade <= 100) { if (0 <= grade && grade <= 100) { pctGrade = newGrade; pctGrade = newGrade; }} May want to print an error message…
51
More Methods Can create other methods if you want stu.printRecord(); prints stu’s name, A-number and grade just uses System.out.println »that’s OK because it’s part of the job! stu number name pctGrade A00123456 “Dent, Stu” 81 A-Number: A00123456 Name: Dent, Stu Grade: 81
52
Calling Own Methods One method can call other methods stu.setNameAndGrade(“Daria”, 100); can call setName and setGrade but who to ask? »Student class doesn’t know the name “stu” public void setNameAndGrade(String n, int g) { stu.setName(n); stu.setName(n); stu.setGrade(g); stu.setGrade(g);} can’t find symbol variable stu
53
What is “this”? Each object’s name for itself public void setNameAndGrade(String n, int g) { this.setName(n); this.setName(n); this.setGrade(g); this.setGrade(g);} calls setName and setGrade for the same object that was asked to set its name and grade stu1.setNameAndGrade(“Bart”, 50); stu2.setNameAndGrade(“Daria”, 100);
54
Instance Constants If an IV never changes, then make it final and then make it public public final String A_NUMBER; Constructor must set its value public Student(String a, String n, int g) { A_NUMBER = a; A_NUMBER = a; …} no other method can change its value
55
Class Variables Better to generate A-numbers automatically can’t accidentally give two students same A-# A variable to keep track of # of students make it private and static, start at 0 private static int numStudents = 0; goes up by 1 with each Student constructed public Student(String n, int pct) { ++numStudents; ++numStudents; …}
56
Static vs. Non-Static non-static each object has its own public final String A_NUMBER; what’s your A-number? » »each student has own answer static shared by all the objects private static int numStudents = 0; how many students are there at SMU? » »same answer for every student tho’ most students won’t know the answer….
57
Automatic Student Numbers Number students from A00000001 set this student’s A-number to new # students format it as required public Student(String n, int pct) { ++numStudents; ++numStudents; A_NUMBER = String.format(“A%08d”, numStudents); A_NUMBER = String.format(“A%08d”, numStudents); …}
58
Class (static) Methods Ask for letter grade corresponding to pct String lg = Student.letterGradeFor(stu.getPctGrade()); doesn’t matter who you ask, answer is same »static method! public static String letterGradeFor(int g) { if (g >= 80) return “A”; else if (g >= 70) return “B”; … if (g >= 80) return “A”; else if (g >= 70) return “B”; …}
59
More Instance Methods Make it easier to get Student’s letter grade S.o.pln(stu.getName() + “ got ” + stu.getLetterGrade()); asks student object for its letter grade method is like a getter… public String getLetterGrade() { return this.getLetterGradeFor(this.getPctGrade()); return this.getLetterGradeFor(this.getPctGrade());} …but don’t create a letterGrade variable!
60
Programming Principles Make it impossible (or very hard) for the client to do stupid/malicious things can’t set pctGrade outside 0..100 can’t set pctGrade to 100 and letterGrade to F Make it easy for client to do common things ask a Student for their letter grade, even tho’ could ask Student for their pctGrade and then translate it using “cascading if” control getLetterGrade is a convenience
61
Another Convenience Printing an object doesn’t work very well! Student stu = new Student(“Pat”, 80); System.out.println(stu); prints something like Student@1f23a want something like Pat (A00000003) toString method tells how to convert an object to a String (which can be printed) System.out.println(stu.toString());
62
The toString Method Does not print anything! it returns the String that will get printed @Override public String toString() { return name + “ (” + A_NUMBER + “)” return name + “ (” + A_NUMBER + “)”} @Override is optional, but NetBeans will tell you to put it there »I’ll explain what it means later this term
63
Using the toString method You can ask for it: Student s = new Student(“Pat”, 80); System.out.println(s.toString()); But you don’t actually need to! Student s = new Student(“Pat”, 80); System.out.println(s); println will actually change it to String itself »one of the conveniences println provides!
64
Questions
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.