Date post: | 21-Dec-2015 |
Category: |
Documents |
View: | 224 times |
Download: | 0 times |
MethodsMethods
Variables describe static aspects– “nouns”
Methods describe dynamic aspects– “verbs”, “behaviors”– Methods “do things”
MethodsMethods
We have occasion to use methods that do computation “elsewhere”– double d1 = Math.sqrt(50.9);
MethodsMethods
Think of a method as a “black box”– We put something in– We get something out
Putting something in– parameters
Getting something out– Return values
A Computer ProgramA Computer Program
public class myFirstProg {
public static void main(String args[]){
System.out.println(“Hello, CSC171”);
}
}
A Computer ProgramA Computer Programpublic class mySecondProg {
public static void main(String args[]){int x = 5, y = 8;int product = mymult(x,y);System.out.println( x + “ * “ + y + “ is “ +
product);}public static int mymult(int n1, int n2){
return n1 * n2;}
}
Proceedural AbstractionProceedural Abstraction
We define the input and output behavior– Contract
We embed some complex behavior in a method.
We refer to the method by a nameWe can write & debug the method once &
then use it whenever we want.
public class myThirdProg {public static void main(String args[]){
int x = 5, y = 8;int product = mymult(x,y);System.out.println( x + “^3 * “ + y + “ is “
+ product);}public static int mymult(int n1, int n2){
return mycube(n1) * n2;} public static int mycube(int x){ return x * x * x; }
}
Sequence of eventsSequence of eventsmain()
mymult()
System.out.println()
5,8
1000
“5^3 * 8 is 1000”
void
mycube()
5
125
Group ExerciseGroup Exercise
Write a method – Called “volume of a box”– Takes width, height, depth as parameters– Returns the volume, the product
SolutionSolution
public static int volume (int width, int height, int depth){return width * height * depth;
}
CONSTRUCTORSCONSTRUCTORS
Constructors are special methods
- used to build objects
- you need constructors to build objects out of class definitions
- however, if you don’t specify a constructor, you get one by default
Constructor for InitializationsConstructor for Initializationsclass Instructor {
String name;int age;
public Instructor (String instructorName) {name = instructorName;
}// but you give up your default constructor;}
Accessor/MutatorsAccessor/Mutators
Accessor methods “gets” and Mutator methods “sets” are preferable methodologies rather than direct modification
SoSo
Good:
Instructor i1 = new Instructor();
i1.setName(“Ted”);
Bad:
Instructor i1 = new Instructor();
i1.name = “Ted”;