Methods & Classeswilliams.comp.ncat.edu/COMP163/Methods3.pdf•Math and Double are examples of...
Transcript of Methods & Classeswilliams.comp.ncat.edu/COMP163/Methods3.pdf•Math and Double are examples of...
Methods & Classes
COMP163
“Few things can help an individual more
than to place responsibility on him, and
to let him know that you trust him.”
Booker T. Washingtonreformer, educator and author
(1856-1915)
ZyBooks
• Read chapter 9 of the ZyBooks text and answer all of the participation questions
• Due by midnight on Sunday, November 3, 2019
Freshman Mock Interviews
• Mock interviews will allow students to put theory and practice together by actually participating in a mock technical interview conducted by Google engineers. Students will receive on the spot feedback and ways to continue preparing for upcoming interviews.
• When: November 7, 2019 from 9:00 am to 5:00 pm
• Where: Murphy Hall 101
• RSVP: http://bit.ly/2Jt4tbU
Local Variables
• Variables declared inside a method are known as local variables or automatic variables
• Variables declared inside the main method are also local variables
• Local variables can only be used inside the method where they are declared
Local Variable Examples
• The variables we use in Java applications are usually local variables
public class StopWatch {
public static void main(String[] unused) {
java.util.Scanner keyboard = new
java.util.Scanner(System.in);
int dog, rabbit;
• keyboard, dog and rabbit are local variables
Parameter Variables
• In addition to local variables, a method can use its parameter variables
double avg( int dog, int cat ) {
double sum = dog + cat;
return sum / 2.0;
}
• sum is a local variable while dog and cat are parameter variables
Class Data• An object can have data variables called Fields,
Properties or Instance variables
• Data can be primitive data types, such as double or int, or other objects
• A class encapsulates data values that form a logical entity, such as
– Information about a student in class
– phone book
– picture
Class Variablespublic class Reptile {
int skink = 11;
int doit( int toad ){
int lizard = skink + toad;
return lizard;
}
}
• skink is an instance variable
• toad is a parameter variable
• lizard is a local variable
What is displayed?
public static void main(String[] hare) {int kitten, bunny = 5;kitten = amebae( bunny );System.out.print("main "+bunny);
}static int amebae( int ecoli ) {
ecoli = ecoli + 3;System.out.print("microbe " + ecoli);return ecoli;
}
A.microbe 8 main 5B.microbe 8 main 8C.main 5 microbe 8D.main 8 microbe 8E.none of the above
Calling a Method in the same Class
• A call to a method in the same class needs the method name followed by the arguments
myMethod( a, b );
11
Calling a Method in Another Class
• A call to a static method in the another class needs the class name, a period, the method name followed by the arguments
YourClass.myStaticMethod( a, b );
• Math and Double are examples of classes with static methods
12
Calling a Method in Another Class
• A call to a non-static method in the another class needs an object’s variable name, a period, the method name followed by the arguments.
YourClass myObject = new YourClass();
myObject.myDynamicMethod( a, b );
• The Scanner class has non-static methods
13
Write a method to average two numbers
• Write a simple method (ignore any class definition for now) that averages two double numbers
Write a method to average two numbers
• The method will need two parameters of type double
• The return value of the method will be the average and should be a double
A method to average two numbers
double average( double num1, double num2) {
return (num1 + num2) / 2.0;
}
A method to average two numbers
double average( double num1, double num2) {
double avg = (num1 + num2) / 2.0;
return avg;
}
Incorrect
double average( double num1, double num2) {
num1 = keyboard.nextDouble();
num2 = keyboard.nextDouble();
double avg = (num1 + num2) / 2.0;
System.out.println(“avg = “ + avg );
return avg;
}
Methods calling Methodsint dog = 5, cat;
cat = methA( dog ); // dog = 5
int methA( int cow ) {
int bull = 2 * cow;
steer = methB( bull )
return steer
}
int methB( int lizard ) {
return lizard + 3;
}
Methods calling Methodsint dog = 5, cat;
cat = methA( dog );
int methA( int cow ) { // cow = 5
int bull = 2 * cow;
steer = methB( bull )
return steer
}
int methB( int lizard ) {
return lizard + 3;
}
Methods calling Methodsint dog = 5, cat;
cat = methA( dog );
int methA( int cow ) { // cow = 5
int bull = 2 * cow; // bull = 10
steer = methB( bull )
return steer
}
int methB( int lizard ) {
return lizard + 3;
}
Methods calling Methodsint dog = 5, cat;
cat = methA( dog );
int methA( int cow ) { // cow = 5
int bull = 2 * cow; // bull = 10
steer = methB( bull )
return steer
}
int methB( int lizard ) { // lizard = 10
return lizard + 3;
}
Methods calling Methodsint dog = 5, cat;
cat = methA( dog );
int methA( int cow ) { // cow = 5
int bull = 2 * cow; // bull = 10
steer = methB( bull )
return steer
}
int methB( int lizard ) { // lizard = 10
return lizard + 3; // returns 13
}
Methods calling Methodsint dog = 5, cat;
cat = methA( dog );
int methA( int cow ) { // cow = 5
int bull = 2 * cow; // bull = 10
steer = methB( bull ) // steer 13
return steer
}
int methB( int lizard ) { // lizard = 10
return lizard + 3; // returns 13
}
Methods calling Methodsint dog = 5, cat;
cat = methA( dog );
int methA( int cow ) { // cow = 5
int bull = 2 * cow; // bull = 10
steer = methB( bull ) // steer 13
return steer // returns 13
}
int methB( int lizard ) { // lizard = 10
return lizard + 3; // returns 13
}
Methods calling Methodsint dog = 5, cat;
cat = methA( dog ); // cat = 13
int methA( int cow ) { // cow = 5
int bull = 2 * cow; // bull = 10
steer = methB( bull ) // steer 13
return steer // returns 13
}
int methB( int lizard ) { // lizard = 10
return lizard + 3; // returns 13
}
What is displayed ?static int trout(int cat) {
System.out.print( " trout "+cat );
return 3 * cat;
}
static int bass(int dog) {
System.out.print(" bass "+ dog );
return trout( dog + 2);
}
static public void main(String[] x) {
int cow = bass( 1 );
System.out.println( " main "+cow );
}
static int carp(int goat) {
System.out.println(" carp "+ goat );
return 2 * goat;
}
A.trout 3 bass 2 main 1B.bass 1 trout 3 main 9C.bass 2 carp 2 trout 3D.bass 1 trout 1 main 5E.none of the above
Class Instance & Local Variables
• Local variables in methods are reset every time you call the method
• Data in object instance variables last for the life of the object
• Data in a static instance variables last for the life of the program
Persistent Data
• Instance variables are created when the object is created. Instance variable memory is released when the object is deleted
• Local variables are created when a method is called. Local variable memory is released when the method returns
• If you change an instance variable it stays changed
• Local variables are reset each call
Instance Variable Exampleint raccoon = 2, otter;
KeepIt fox = new KeepIt();
otter = fox.grizzly( raccoon );
class KeepIt {
int bear = 3;
public int grizzly( int cub ) {
bear = bear + cub;
return bear * cub;
}
}
What is printed?
A. 1
B. 3
C. 4
D. 10
E. none of the above
KeepIt fox = new KeepIt();
otter = fox.grizzly( 1 );
System.out.println(otter);
Now what is printed?
A. 4 4
B. 4 5
C. 4 6
D. 4 12
E. none of the above
KeepIt fox = new KeepIt();
otter = fox.grizzly( 1 );
System.out.print (otter);
otter = fox.grizzly( 2 );
System.out.println(otter);
Javadoc
• Javadoc is a tool to create webpages that document your program
• Programs have to contain specially formatted comments
• Javadoc comments start with /** and end with */
• You can put Javadoc comments before methods, classes or fields
Documenting Classes
• Javadoc comments start with /** and end with */
• A class must start with a Javadoc comment
/**
Description of the program. More details.
@author your name
*/
javadoc for Methods
• You should put a javadoc comment before every method defining what the method does
• The first sentence of your description will be used as the short description of the method
• You should also include
–@param for each parameter
–@return unless it is a void method
@param
• The @param command should be in a Javadoc comment before a method
• The @param command describes the meaning of an input parameter to the method
• For each parameter use
@param parametername description
• where description is a sentence or more describing the use of the parameter
Using @param
/**
* This method hacks into the
* instructor’s computer and changes
* your grade.
* @param id Your Banner ID.
* @param grade Your desired grade.
*/
void hack( int id, String grade) {
@return
• The @return command should be in a Javadoc comment before a method header
• You do not need @return for void methods
• @return describes the meaning of the value being returned
/** Method to do something.
* @return The calculated something or zero.
*/
javadoc Example/**
* This is an example.
* @author Ken Williams
*/
public class DocPage {
/**
* Compute the area of a rectangle.
* @param high The height of the rectangle. The
* height is the vertical dimension.
* @param wide The width of the rectangle.
* @return The area of the rectangle.
*/
public double area(double high, double wide) {
Javadoc is Required
• For all programs for weekly assignments and labs, you must use Javadoc style comments
• There must be a Javadoc formatted comment before each class (beginning of the program)
• Each method (except the main method) must start with a Javadoc comment
• All variables must be commented as before
– You can use the // style for variables
Variable Scope• The “Scope” of a variable refers to where you can use
the variable
• Where you declare a variable determines where it can be used
• The variable names used in a method are a completely separate set of names from the names used in any other method, including the main method
Variable Range• Variables defined in a block can only be used in
that block following the variable declaration{
// you cannot use the variable moth heredouble moth = 72.5;
// you may use the variable moth here// this is the scope of moth
}// The variable moth is not allowed here
Name Collision
public class Collide {
int rat = 3;
public int square( int rat ) {
return rat * rat;
}
}
Collide thing = new Collide();
int turtle = thing.square( 2 );
• turtle is set to 4
Variable Priority
• A method cannot have a local variable the same name as a parameter variable
• If a object instance variable has the same name as a local variable or parameter, the method will always use the local variable or parameter
What is printed by this program?
A. 4 4
B. 4 5
C. 5 5
D. none of above
public class Click {static int crow= 5, raven= 7;static void myfunc(int parrot) {
int crow;crow = parrot + 1;System.out.print( crow );
}public static void main(…) {
Click ques = new Click();ques.myfunc( 3 );System.out.print( crow );
} }
What is printed by this program?
A. 4 4
B. 4 5
C. 5 5
D. none of above
public class Click {static int crow= 5, raven= 7;static void myfunc(int parrot) {
// changed here
crow = parrot + 1;System.out.print( crow );
}public static void main(…) {
Click ques = new Click();ques.myfunc( 3 );System.out.print( crow );
} }
Resolving Name Collision with this
public class Collide {
int rat = 3;
public int square( int rat ) {
return this.rat * rat;
}
}
Collide thing = new Collide();
int turtle = thing.square( 2 );
• turtle gets the value 6
Static Variables
• Class variables can be specified as static
public class electric {
static int cat; // static class variable
int dog; // non- static class variable
}
• There is only one copy of a static variable shared by all objects of that class
• There is a separate copy of non-static variables for each object
Multiple Objectspublic class Electric {
static int cat = 1;int dog = 2;
}
Electric possum = new Electric();Electric rat = new Electric();Electric mouse = new Electric();
• There are three Electric objects
• Each object has its own copy of dog
• There is only one cat variable
Static and Instance Variables
• There is only one cat variable, but there is a dog for every object
Electric classcat
Electric object
dog
Electric object
dog
Electric object
dog
1
2 2 2
Using Instance Variablespublic class Electric {
static int cat = 1;int dog = 2;public void cat2() {
cat = cat + 2;}public void dog3() {
dog = dog + 3;}public void prtCat() {
System.out.println(cat);}public void prtDog() {
System.out.println(dog);}
}
Electric volt = new Electric();Electric watt = new Electric();volt.cat2();watt.dog3(); displaysvolt.prtCat(); 3volt.prtDog(); 2watt.prtCat(); 3watt.prtDog(); 5
What is displayed?public class Stest {
static int svar = 1;
int dvar = 1;
void incBoth() {
svar++;
dvar++;
System.out.println(svar+" "+dvar);
}
static public void main(String[] x) {
Stest cat = new Stest();
Stest dog = new Stest();
cat.incBoth();
dog.incBoth();
}
}
A. 1 11 1
B. 2 22 2
C. 2 23 3
D. 2 23 2
Only One Copy of Static Variablespublic class Egg {
static int yolk;
int whites;
public Egg(int frog, int toad) {
yolk = frog;
whites = toad;}
}
// --------- In another class -----------
Egg bird = new Egg( 2, 4 );
Egg lizard = new Egg( 3, 5 );• frog• toad
Egg yolk
bird
Only One Copy of Static Variablespublic class Egg {
static int yolk;
int whites;
public Egg(int frog, int toad) {
yolk = frog;
whites = toad;}
}
// --------- In another class -----------
Egg bird = new Egg( 2, 4 );
Egg lizard = new Egg( 3, 5 );
Egg yolk2
bird whites
frog toad
2 4
Only One Copy of Static Variablespublic class Egg {
static int yolk;
int whites;
public Egg(int frog, int toad) {
yolk = frog;
whites = toad;}
}
// --------- In another class -----------
Egg bird = new Egg( 2, 4 );
Egg lizard = new Egg( 3, 5 );
Egg yolk2
bird whites4
frog toad
2 4
Only One Copy of Static Variablespublic class Egg {
static int yolk;
int whites;
public Egg(int frog, int toad) {
yolk = frog;
whites = toad;}
}
// --------- In another class -----------
Egg bird = new Egg( 2, 4 );
Egg lizard = new Egg( 3, 5 );
Egg yolk2
bird whites4
lizard
Only One Copy of Static Variablespublic class Egg {
static int yolk;
int whites;
public Egg(int frog, int toad) {
yolk = frog;
whites = toad;}
}
// --------- In another class -----------
Egg bird = new Egg( 2, 4 );
Egg lizard = new Egg( 3, 5 );
Egg yolk3
bird whites4
lizard whites
frog toad
3 5
Only One Copy of Static Variablespublic class Egg {
static int yolk;
int whites;
public Egg(int frog, int toad) {
yolk = frog;
whites = toad;}
}
// --------- In another class -----------
Egg bird = new Egg( 2, 4 );
Egg lizard = new Egg( 3, 5 );
Egg yolk3
bird whites4
lizard whites5
frog toad
3 5
Static and Dynamic
• A non-static variable can only be accessed by non-static methods
• Non-static variables belong to the object
• A static variable can be accessed by any method
• Static variables belong to the class
Static and Dynamic Examplepublic class Program {static int statData = 3;int dyData = 1;void inc() { // non-static method
dyData++;statData++;
}public static void main(String[] x) {
Program thing = new Program();Program other = new Program();thing.inc();statData = 2;dyData = 5; // not Allowedthing.dyData = 7; // this is allowed
}}
Static or Dynamic ?
• If a method uses class instance variables, it cannot be static
• If a method does not use any class instance variables, it can be static
Instance and Local Examplepublic class PermTemp {
static int aardvark = 1;
public static void main(String[] uu) {
addTo( 2 );
addTo( 1 );
}
static void addTo( int ant ) {
int termite = 7;
aardvark = aardvark + ant;
termite = termite + ant;
System.out.println( termite+" "+ aardvark);
}
}
Output
aardvark termite ant
1
Instance and Local Examplepublic class PermTemp {
static int aardvark = 1;
public static void main(String[] uu) {
addTo( 2 );
addTo( 1 );
}
static void addTo( int ant ) {
int termite = 7;
aardvark = aardvark + ant;
termite = termite + ant;
System.out.println( termite+" "+ aardvark);
}
}
Output
aardvark termite ant
1 7 2
Instance and Local Examplepublic class PermTemp {
static int aardvark = 1;
public static void main(String[] uu) {
addTo( 2 );
addTo( 1 );
}
static void addTo( int ant ) {
int termite = 7;
aardvark = aardvark + ant;
termite = termite + ant;
System.out.println( termite+" "+ aardvark);
}
}
Output
aardvark termite ant
3 7 2
Instance and Local Examplepublic class PermTemp {
static int aardvark = 1;
public static void main(String[] uu) {
addTo( 2 );
addTo( 1 );
}
static void addTo( int ant ) {
int termite = 7;
aardvark = aardvark + ant;
termite = termite + ant;
System.out.println( termite+" "+ aardvark);
}
}
Output
aardvark termite ant
3 9 2
Instance and Local Examplepublic class PermTemp {
static int aardvark = 1;
public static void main(String[] uu) {
addTo( 2 );
addTo( 1 );
}
static void addTo( int ant ) {
int termite = 7;
aardvark = aardvark + ant;
termite = termite + ant;
System.out.println( termite+" "+ aardvark);
}
}
Output9 3
aardvark termite ant
3 9 2
Instance and Local Examplepublic class PermTemp {
static int aardvark = 1;
public static void main(String[] uu) {
addTo( 2 );
addTo( 1 );
}
static void addTo( int ant ) {
int termite = 7;
aardvark = aardvark + ant;
termite = termite + ant;
System.out.println( termite+" "+ aardvark);
}
}
Output9 3
aardvark termite ant
3
Instance and Local Examplepublic class PermTemp {
static int aardvark = 1;
public static void main(String[] uu) {
addTo( 2 );
addTo( 1 );
}
static void addTo( int ant ) {
int termite = 7;
aardvark = aardvark + ant;
termite = termite + ant;
System.out.println( termite+" "+ aardvark);
}
}
Output9 3
aardvark termite ant
3 7 1
Instance and Local Examplepublic class PermTemp {
static int aardvark = 1;
public static void main(String[] uu) {
addTo( 2 );
addTo( 1 );
}
static void addTo( int ant ) {
int termite = 7;
aardvark = aardvark + ant;
termite = termite + ant;
System.out.println( termite+" "+ aardvark);
}
}
Output9 3
aardvark termite ant
4 7 1
Instance and Local Examplepublic class PermTemp {
static int aardvark = 1;
public static void main(String[] uu) {
addTo( 2 );
addTo( 1 );
}
static void addTo( int ant ) {
int termite = 7;
aardvark = aardvark + ant;
termite = termite + ant;
System.out.println( termite+" "+ aardvark);
}
}
Output9 3
aardvark termite ant
4 8 1
Instance and Local Examplepublic class PermTemp {
static int aardvark = 1;
public static void main(String[] uu) {
addTo( 2 );
addTo( 1 );
}
static void addTo( int ant ) {
int termite = 7;
aardvark = aardvark + ant;
termite = termite + ant;
System.out.println( termite+" "+ aardvark);
}
}
Output9 3
8 4
aardvark termite ant
4 8 1
Queuing Theory
• Queuing theory is the mathematics of waiting lines
• It is extremely useful in predicting and evaluating system performance
Single or Multiple Queues
λ
λ /2
λ /2
M/M/N Bank Teller model
M/M/1 Grocery Store model
S
S
S
S
S
Queuing Theory• The probability that all n servers are busy in an
M/M/N system (bank teller model) is C
• whereN
sK
KC
−
−=
1
1
=
−
==N
i i
s
N
i i
s
i
i
K
0 !
)(
1
0 !
)(
Example Method
• Write a method that returns the value C given the three input parameters lambda(λ), s and n
• The method will have the header
double probAllBusy( double lambda, double s, int n)
Solution Outline
• In the equation for K, the denominator is a sum that is the same as the numerator except that it is one term longer
• If we have a method to calculate the sum, the rest of the method is simple
probAllBusy method
double probAllBusy( double lambda,
double s, int n) {
double k = kSum(lambda, s, n-1) /
kSum(lambda, s, n);
return (1.0 - k) / (1.0 – lambda*s*k/n);
}
N
sK
KC
−
−=
1
1
=
−
==N
i i
s
N
i i
s
i
i
K
0 !
)(
1
0 !
)(
kSum method
• The kSum method calculates this sum given the parameters lambda, s and n
• We will need a method to calculate factorials
=
N
i i
s i
0 !
)(
factorial method
• The factorial function in mathematics, n!, is
1 * 2 * 3 * 4 * … * n
• For the special case of zero, 0! = 1
The header for factorial should be
A. int factorial( int n )
B. void factorial( int n, int fac )
C. static factorial( int n )
D. none of the above
Write the factorial method
• With your team, write a method with one integer parameter, n, that returns n!
• Don’t forget the special case for zero
– You might not have to do anything special
Possible Solution
int factorial( int n ) {
int fac = 1;
for (int i =1; i <= n; i++) {
fac = fac * i;
}
return fac;
}
Write the kSum method
• Write a method to calculate this sum given the parameters lambda, s and n
double kSum( double lambda, double s, int n )
=
N
i i
s i
0 !
)(
Possible Solution
double kSum( double lambda, double s, int n ) {
double sum = 0.0;
for (int i = 0; i <= n; i++) {
sum += Math.pow( lambda*s, (double)i ) /
factorial( i );
}
return sum;
}
It looks Greek to me
double kSum( double λ, double s, int n ) {
double sum = 0.0;
for (int i = 0; i <= n; i++) {
sum += Math.pow( λ*s, (double)i ) /
factorial( i );
}
return sum;
}
Small Steps
• The value of using methods is that you can break a larger problem into small steps
• The probAllBusy method called the kSum method twice
• kSum called factorial
• Note that we wrote the program using methods we had not yet written, but knew we could write
Recursion
• (N-1)! is 1 * 2 * 3 * 4 * … * N-1
• N! is 1 * 2 * 3 * 4 * … * N-1 * N
or (N-1)! * N
• If you have a factorial method that computes (N-1)!, you can calculate N! by multiplying the result of the method by N
• You need to be mindful that N-1 might drop to zero
Recursive Solution
int factorial( int n ) {
if (n <= 1) return 1;
return n * factorial( n-1 );
}
ZyBooks
• Read chapter 9 of the ZyBooks text and answer all of the participation questions
• Due by midnight on Sunday, November 3, 2019
Freshman Mock Interviews
• Mock interviews will allow students to put theory and practice together by actually participating in a mock technical interview conducted by Google engineers. Students will receive on the spot feedback and ways to continue preparing for upcoming interviews.
• When: November 7, 2019 from 9:00 am to 5:00 pm
• Where: Murphy Hall 101
• RSVP: http://bit.ly/2Jt4tbU