64
Methods Material from Chapters 5 & 6

Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7 Methods »(AKA subroutines, functions, procedures) understand method calls create

Embed Size (px)

Citation preview

Page 1: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

Methods

Material from Chapters 5 & 6

Page 2: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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

Page 3: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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

Page 4: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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

Page 5: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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

Page 6: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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 typeScanner kbd = new Scanner(System.in);String resp = kbd.nextLine();

Methods are declared in that class class Math, class Scanner, class String, …

Page 7: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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)

Page 8: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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

Page 9: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

Void Methods

Some methods are complete commands in themselves telling the computer to do somethingSystem.out.println(“A complete command”);

These methods cannot be used as part of a commandString resp = System.out.println(“What???”);

Page 10: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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 commandint n = kbd.nextInt();double y = Math.sqrt(n);if (resp.startsWith(s)) {

But may be used alone sometimeskbd.nextLine(); // we don’t care what the line was!

Page 11: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

“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”

Page 12: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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

Page 13: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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

Page 14: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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

Page 15: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

Declaring Classes and Methods

Need to declare the class (just like before)public class Converter { ... // methods in here //}

Need to declare the methods (like before)public static ... ... (...) { .... // commands in here //}

Compare:public static void main(String[] args) { ...}

Page 16: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

The Method Header / Interface

First line of the method definitionpublic 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

Page 17: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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)

Page 18: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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

Page 19: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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 valuepublic static double cmFromFeetInches(int ft, double in) { return 0.0;}

Page 20: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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;

}

Page 21: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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 constantspublic class Converter {

public static final int IN_PER_FT = 12;public static final double CM_PER_IN = 2.54;

final = never going to change

Page 22: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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. * * @param ft (whole) number of feet in the

distance * @param in number of (extra) inches in the distance * @return same distance, but measured in centimetres */

Page 23: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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

Page 24: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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 valuefahrenheitFromCelsius(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 righttempInF = fahrenheitFromCelsius(29.0);

just do the math; leave caller to do the I/O

Page 25: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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

Page 26: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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!

Page 27: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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

}

}

Page 28: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

printTitle Body

public static void printTitle(String title) {

System.out.print("\n" + title + "\n");

for (int i = 1; i <= title.length(); i++)

System.out.print('-');

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

Page 29: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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

Page 30: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

Method to Sum an Array

Array comes from callerint[] n = new int[]{2, 3, 5, 7, 11};int addedUp = ArrayOperations.sum(n);

Method adds up its elementspublic static int sum(int[] a) { int sum = 0; for (int i = 0; i < a.length; i++) { sum += a[i]; } return sum;}

TestArrayOperations.javaArrayOperations.java

Page 31: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

Returning Arrays

Methods can return arraysint[] c = ArrayOperations.add(a, b); return type is an array typepublic static int[] add(int[] a, int[] b)

May need to create the array to be returnedint len = Math.min(a.length, b.length);int[] result = new int[len];…return result;

Page 32: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

Classes vs. Objects

Classes can be used right awayUtilities.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

Page 33: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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

Page 34: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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

Page 35: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

Object Classes

What kind of object it is its data type is a ClassString s1, s2; // s1 & s2 are StringsScanner kbd, str; // kbd & str are ScannersAnimal rover, hammy; // rover & hammy are AnimalsColor c1, c2; // c1 & c2 are ColorsJButton 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;

Page 36: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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 orangeokButton = 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;

Page 37: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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

Page 38: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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

Page 39: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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

Page 40: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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

Page 41: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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

Page 42: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

Declaring a Student

Give A#, name and grade when createStudent 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)

Page 43: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

Student Constructor

Constructor “builds” the Student object gives a value to each of the instance variablesprivate String aNumber; // A00…private String name; // Last, Firstprivate int grade; // 0 .. 100public Student(String a, String n, int g) { aNumber = a; name = n; 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.

Page 44: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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)

Page 45: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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

Page 46: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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) { aNumber = a; } else { aNumber = “(illegal)”; } name = n; …}

Page 47: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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 camelCaseSystem.out.println(stu.getName());System.out.println(stu.getANumber());System.out.println(stu.getPctGrade());

name is private in Student!

Page 48: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

Student “Getters”

Getters are very simple! just return the instance variable

» method return type same as type of variableprivate String aNumber; // A00…private String name; // Last, Firstpublic String getName() { return name;}public String getANumber() { return aNumber;}

public!Anyone can ask!

No static!Each student has own name!

Page 49: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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 variablestu.setName(“Dummikins, Dummy”);stu.setPctGrade(1000000);

name is private in Student!

Page 50: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

Setters

Given the new value the caller wants normally we will use that valuepublic static void setName(String newName) { name = newName;} but we might want to reject itpublic static void setPctGrade(int newGrade) { if (0 <= grade && grade <= 100) { pctGrade = newGrade; }}

May want to print an error message…

Page 51: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

More Methods

Can create other methods if you wantstu.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: A00123456Name: Dent, StuGrade: 81

Page 52: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

Calling Own Methods

One method can call other methodsstu.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.setGrade(g);}

can’t find symbolvariable stu

Page 53: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

What is “this”?

Each object’s name for itselfpublic void setNameAndGrade(String n, int g) { this.setName(n); this.setGrade(g);} calls setName and setGrade for the same object

that was asked to set its name and gradestu1.setNameAndGrade(“Bart”, 50);stu2.setNameAndGrade(“Daria”, 100);

Page 54: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

Instance Constants

If an IV never changes, then make it final and then make it publicpublic final String A_NUMBER;

Constructor must set its valuepublic Student(String a, String n, int g) { A_NUMBER = a; …} no other method can change its value

Page 55: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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 0private static int numStudents = 0; goes up by 1 with each Student constructedpublic Student(String n, int pct) { ++numStudents; …}

Page 56: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

Static vs. Non-Static

non-static each object has its ownpublic final String A_NUMBER; what’s your A-number?

» each student has own answer

static shared by all the objectsprivate static int numStudents = 0; how many students are there at SMU?

» same answer for every student• tho’ most students won’t know the answer….

Page 57: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

Automatic Student Numbers

Number students from A00000001 set this student’s A-number to new # students format it as requiredpublic Student(String n, int pct) { ++numStudents; A_NUMBER = String.format(“A%08d”, numStudents); …}

Page 58: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

Class (static) Methods

Ask for letter grade corresponding to pctString 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”;…

}

Page 59: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

More Instance Methods

Make it easier to get Student’s letter gradeS.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());} …but don’t create a letterGrade variable!

Page 60: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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

Page 61: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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

Page 62: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

The toString Method

Does not print anything! it returns the String that will get printed@Overridepublic String toString() { 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

Page 63: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

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!

Page 64: Methods Material from Chapters 5 & 6. Review of Chapters 5 to 7  Methods »(AKA subroutines, functions, procedures)  understand method calls  create

Questions