|
6. Methods
Objectives:
To understand how parameters are passed into methods and how values are returned from methods
To understand the difference between instance methods and static methods
To introduce the concept of static variables; the scope of variables
To be able to program recursive methods
Method Parameters
public class BankAccount
{ …public void deposit(double amount)
{ …
}
...
}
This method has two formal parameters:
implicit parameter this; explicit parameter amount
myChecking.deposit(allowance-200);
this = myChecking;
amount = allowance – 200;
Parameters
The parameter amount is called an explicit parameter because it is explicitly named in the method definition.
The parameter this (the bank account reference) is called an implicit parameter because it is not explicit in the method definition.
When you call a method, you supply the value for the implicit parameter before the method name, separated by a dot (.), and you supply the values for the explicit parameters inside parentheses after the method name:
implicitParameter.methodName(explicitParameter);
myChecking.deposit(allowance - 200);
This method Call, supply two actual parameters or arguments.
The object reference stored in the variable myChecking.
The value of the expression allowance – 200.
When a method is called, the actual parameter values are computed and copied into the formal parameter variables.
public class BankAccount
{… public void transfer(BankAccount other, double amount)
{ withdraw(amount);
other.deposit(amount);
}…
}
For example,
double allowance = 800;
momsSaving.transfer(myChecking, allowance);
this = momsSaving;
double allowance = 800;
momsSaving.transfer(myChecking, allowance);
Accessor Methods & Mutator Methods
A method that accesses an object and returns some information without changing the object is called an accessor method.
For example, in the BankAccount class, getBalance is an accessor method.
A method that modifies the state of an object is called a mutator method.
For example, the deposit/withdraw methods are mutator methods.
Static Methods
A static method or a class method is a method that does not need an implicit parameter.
A method that needs implicit parameter is called an instance method because it operates on a particular instance of an object.
For example, the sqrt of the Math class is a static method because we don’t need to supply any implicit parameter.
The reason that we want to write a static method is because we want to encapsulate some computations that involves only numbers.
Static Method
Two floating-point numbers x and y are approximately equal ifThe parameters are only numbers and the method doesn’t operate on any objects
so we can make it into a static method:
class Numeric
{ public static boolean approxEqual(double x, double y)
{ final double EPSILON = 1E-14;
double xymax = Math.max(Math.abs(x), Math.abs(y));
return Math.abs(x - y) <= EPSILON * xymax;
}…
}
Static Method
When calling the static method, you supply the name of the class containing the method:
double r = Math.sqrt(2);
if (Numeric.approxEqual( r*r, 2))
System.out.println(“Math.sqrt(2) squared is apporx 2”);
The main method is static because when the program starts, there isn’t any objects yet.
The static method means “class method”.
Call by Value/Call by Reference
Trying to modify numeric parameters
public static void updateBalance(double balance, double intRate)
{ double interest = balance * intRate / 100;
balance = balance + interest;
}
public static void main(String[] args)
{ double savings = 10000, rate = 5;
updateBalance(savings, rate);
// savings is not updated
….
}
A method can modify the state of object parameters
public static void updateBalance(BankAccount account,
double intRate)
{ double interest = account.getBalance() * intRate / 100;
account.deposit(interest);
}
public static void main(String[] args)
{ BankAccount collegeFund = new BankAccount(10000);
double rate = 5;
updateBalance(collegeFund, rate);
…
}
“numbers are passed by value, objects are passed by referece” is not quite correct.
public static void chooseAccount(BankAccount betterAccount,
BankAccount candidate1, BankAccount candidate2)
{ if (candidate1.getBalance() > candidate2.getBalance())
betterAccount = candidate1;
else
betterAccount = candidate2;
}
public static void main(String[] args)
{ BankAccount collegeFund = new BankAccount(10000);
BankAccount momAcc = new BankAccount(8000);
BankAccount myAccount = null;
chooseAccount(myAccount, momAcc, collegeFund); // ?
…
}
public static BankAccount chooseAccount(BankAccount candidate1,
BankAccount candidate2)
{ BankAccount betterAccount;
if (candidate1.getBalance() > candidate2.getBalance())
betterAccount = candidate1;
else
betterAccount = candidate2;
return betterAccount;
}
public static void main(String[] args)
{ BankAccount collegeFund = new BankAccount(10000);
BankAccount momAcc = new BankAccount(8000);
BankAccount myAccount;
myAccount = chooseAccount(momAcc, collegeFund); // ?
…
}
The return Statement
A method that has a return type other than void must return a value, by executing
return expression;
Missing Return Value
public static int sign(double x)
{ if (x < 0) return -1;
if (x > 0) return +1;
// Error: missing return value if x == 0
}
Static Variables
public class BankAccount
{ private double balance;
private int accountNumber;
private int lastAssignedNumber;
}
public class BankAccount
{ private double balance;
private int accountNumber;
private static int lastAssignedNumber;
}
How to initialize static variables?
public BankAccount( )
{ lastAssignedNumber = 0; // ?
…
}
public class BankAccount
{ … private static int lastAssingedNumber = 0;
}
public class Math
{ … public static final double PI = 3.141592653589793238456;
}
Math.PI
Static variable is initialized with 0 (for numbers), false (for boolean), null (for objects).
Variable Lifetime and Scope
Four kinds of variables: Instance variables, Static variables, Local variables, and Parameter variables.
public void withdraw(double amount)
{ if (amount <= balance)
{ double newBalance = balance - amount;
balance = newBalance;
}
}
Shadowing
public class Coin
{ public Coin(double aValue, String aName)
{ value = aValue;
String name = aName; // local variable
}
…
private double value;
private String name; // instance variable
public Coin(String name, double value)
{ this.name = name;
this.value = value;
}
Calling One Constructor from Another
public class BankAccount
{ public BankAccount(double initialBalance)
{ balance = initialBalance;
}
public BankAccount()
{ this(0);
}
}
Comments
/**
Computes the maximum of two integers.
@param x an integer
@param y another integer
@return the larger of the two inputs
*/
public static int max(int x, int y)
{ if (x > y)
return x;
else
return y;
}
javadoc MyProg.java
Recursion
public static int factorial(int n)
{ if (n == 0)
return 1;
else
{ int result = n * factorial(n - 1);
return result;
}
}
Exercise
Write an application using classes and methods to draw a fan and to make its pedals rotated. |
|