Static methods - La Salle University

Download Report

Transcript Static methods - La Salle University

Chapter 5
More About
Objects and Methods







Chapter 5
Programming with Methods
Static Methods and Static Variables
Designing Methods
Polymorphism
Constructors
Information Hiding Revisited
Packages
Java: an Introduction to Computer Science & Programming - Walter Savitch
1
Methods Calling Methods
/*******************************************************
* score a two point shot (regular field goal) for a given team
**/
public int makeTwoPoint(String team) {
int newScore = addPoints(team,2);
return newScore;
}
 makeTwoPoint called from main
 addPoints called from makeTwoPoint
 Since calling for same object, don’t need object.method()
» Same object is the default
» In fact, we have been doing the same thing with instance variables already
» Could call with
this.addPoints(team,2);
» where this is a keyword standing for the same object
 <Show how code transfers control – maybe using debugger>
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
3
Oh, By the way – addPoints is private
/*******************************************************
* helper function for all scoring
*
* Only used internally - main should go through specific types of scoring
*/
private int addPoints (String team, int points) {
// ensure not negative points
if (points <= 0) {
System.out.println("ERROR - cannot add negative or zero points");
return -9;
}
if (team.equals(homeTeamName) || team.equalsIgnoreCase("home") ) {
homeTeamPoints += points;
return homeTeamPoints;
}
else if (team.equals(awayTeamName) || team.equalsIgnoreCase("away") ) {
awayTeamPoints += points;
return awayTeamPoints;
}
else {
System.out.println("ERROR - team not found");
return -1;
}
}
Chapter 5
“Helper Method”
Only intended to
be used my other
methods in
Scoreboard class
– not by main
• More info hiding!
Java: an Introduction to Computer Science & Programming - Walter Savitch
4
Static Methods


Some methods have work to do, but do not need an object in order to do it
E.g. book-provided methods:
» SavitchIn class defines methods for keyboard input
– not automatically provided with Java
– functions include readLineInt, readLineDouble, etc.



– Called using SavitchIn.readLineInt()
– Not called with an object, but rather a class
Such methods are called Static methods
Static methods are commonly used to provide libraries of useful and
related functions
Static methods are sometimes referred to as class methods
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
6
Uses for Static Methods

More Examples:
» the Math class
–automatically provided with Java
–functions include pow, sqrt, max, min,
etc.
–see the next slide for more details
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
8
The Math Class
Includes constants Math.PI (approximately 3.14159) and Math.E
(base of natural logarithms which is approximately 2.72)
 Includes three similar static methods: round, floor, and ceil
» All three return sort-of whole numbers (although they are types
long and double)
» Math.round returns the long whole number nearest its
argument
Math.round(3.3) returns 3 and Math.round(3.7) returns 4
» Math.floor returns the nearest whole number that is equal to or
less than its argument
Math.floor(3.3) returns 3.0 and Math.floor(3.7) returns 3.0
» Math.ceil (short for ceiling) returns the nearest whole number
that is equal to or greater than its argument
Math.ceil(3.3) returns 4.0 and Math.ceil(3.7) returns 4.0


(Must cast to int in order to assign into an int variable)
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
9
Static Methods
Declare static methods with the static modifier, for
example:
public static double area(double radius){
return Math.PI*radius*radius;
} // Math.PI has been declared in Math class



Chapter 5
Since a static method doesn’t need a calling object, it
cannot refer to a (nonstatic) instance variable of the
class.
Likewise, a static method cannot call a nonstatic method
of the class (unless it creates an object of the class to
use as a calling object).
Java: an Introduction to Computer Science & Programming - Walter Savitch
10
Wrapper Classes



Used to wrap primitive types in a class structure
All primitive types have an equivalent class
The class includes useful constants and static methods, including one to
convert back to the primitive type
Chapter 5
Primitive type Class type
Method to convert back
int
Integer
intValue()
long
Long
longValue()
float
Float
floatValue()
double
Double
doubleValue()
char
Character
charValue()
Java: an Introduction to Computer Science & Programming - Walter Savitch
12
Wrapper class examples




Declare an Integer class variable:
Integer n = new Integer(42);
Convert the value of an Integer variable to its primitive type, int:
int i = n.intValue();//intValue returns an int
We have already used wrapper classes a little bit when
we used GUI I/O:
priceString = JOptionPane.showInputDialog("Please enter the price of the
pizza:"); double price;
price = Double.parseDouble(priceString); // static method of Double class // converts a String to a double (primitive type)
Some useful Integer constants:
» Integer.MAX_VALUE - the maximum integer value the computer can
represent
» Integer.MIN_VALUE - the smallest integer value the computer can
represent
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
13
Usage of wrapper classes
There are some important differences in the code to
use wrapper classes and that for the primitive types
Wrapper Class
 variables contain the address of the
value
 variable declaration example:
Integer n = new Integer();


variable declaration & init:
Integer n = new
Integer(0);
assignment:
n = new Integer(5);
Chapter 5
Primitive Type
 variables contain the value

variable declaration example:
int n;

variable declaration & init.:
int n = 0;

assignment:
n = 99;
Java: an Introduction to Computer Science & Programming - Walter Savitch
15
Overloading



Means that the same method name has more than one
definition within the same class
E.g. with a String, there are more than one version of
methods: compareTo, indexOf, substring, valueOf, …
Each definition must have a different signature (heading)
» different argument types, a different number of arguments,
or a different ordering of argument types
» The return type is not part of the signature and cannot be
used to distinguish between two methods with the same
name and parameter types
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
19
Overloading Example – from
Account Class
// determine if a passed string is the correct account number for the calling object
public boolean matchAcctNum(String toCompare) {
if (acctNum.equals(toCompare)) {
return true;
}
else {
return false;
}
}
// determine if a passed account has the same account number as the calling object
public boolean matchAcctNum(Account toCompare) {
if (acctNum.equals(toCompare.getAcctNum())) {
return true;
}
else {
return false;
}
}
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
20
How does it Know?





Compiler determines which method is being called based on the method heading
Some setup code useful for either version
Account myAcct = new Account();
myAcct.setAcctNum(“1234”);
System.out.println(“Please enter your account number”);
String anotherAcctNum = SavitchIn.readLine();
First version called:
boolean match = myAcct.matchAcctNum(anotherAcctNum);
Second version called:
Account anotherAcct = new Account();
anotherAcct.setAcctNum(anotherAcctNum);
boolean match = myAcct.matchAcctNum(anotherAcct);
This looks like the basis for a test question
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
21
Overloading



Chapter 5
Is actually very common
Makes it possible to make your class very flexible – friendly to
the programmers that use it
We have hidden it from you so far because it is a little advanced
Java: an Introduction to Computer Science & Programming - Walter Savitch
22
Constructors




Chapter 5
A constructor is a special method designed to initialize instance
variables
Automatically called when an object is created using new
Has the same name as the class
Often overloaded (more than one constructor for the same class
definition)
» different versions to initialize all, some, or none of the
instance variables
» each constructor has a different signature (a different
number or sequence of argument types)
Java: an Introduction to Computer Science & Programming - Walter Savitch
26
Constructors





Chapter 5
Forte has created constructors automatically for us – constructors that
initialize none of the instance variables
E.g.
/** Creates new Account */
public Account() {
}
E.g.
/** Creates new ScoreBoard */
public ScoreBoard() {
}
These basically allow the default values to be used
These actually run (doing nothing!) when we write declarations such as:
Account myAcct = new Account(); // calls constructor above !!!!
Java: an Introduction to Computer Science & Programming - Walter Savitch
27
Since we hadn’t covered constructors yet …

We wrote code like …
Account myAcct = new Account();
// set up one initial account
System.out.println("Please enter the account number to be used in this simulation");
String acctNum = SavitchIn.readLine();
myAcct.setAcctNum(acctNum);
System.out.println("Please enter the 4 digit PIN to be used in this simulation");
String pin = SavitchIn.readLine();
myAcct.setPIN(pin);
System.out.println("Please enter the beginning balance to be used in this simulation");
double bal = SavitchIn.readLineDouble();
myAcct.setBal(bal);
System.out.println("Please enter the interest rate to be used in this simulation (NOTE 2% is written .02)");
double rate = SavitchIn.readLineDouble();
myAcct.setIntRate(rate);
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
28
But suppose we had a different
constructor available?
/** Creates new Account */
public Account(String acct, String pin, double amt, double rate)
{
acctNum = acct;
PIN = pin;
balance = amt;
intRate = rate;
}
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
29
Then instead of creating an account
and asking questions later …

We could ask questions, then create an account
// set up one initial account
System.out.println("Please enter the account number to be used in this simulation");
String acctNum = SavitchIn.readLine();
System.out.println("Please enter the 4 digit PIN to be used in this simulation");
String pin = SavitchIn.readLine();
System.out.println("Please enter the beginning balance to be used in this simulation");
double bal = SavitchIn.readLineDouble();
System.out.println("Please enter the interest rate to be used in this simulation (NOTE 2% is written .02)");

double rate = SavitchIn.readLineDouble();
Account myAcct = new Account(acctNum,pin,bal,rate);
Admittedly, this is a small savings (9 LOC instead of 13), but gives programmer using
the class flexibility!!!!
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
30
Defining Constructors



Constructor headings do not include a return type
A constructor with no parameters is called a default constructor
If no constructor is provided Java automatically creates a default
constructor
» If any constructor is provided, then no constructors are
created automatically
Programming Tip
 Include a constructor that initializes all instance variables
 Include a constructor that has no parameters
» include your own default constructor
» Forte does this for you
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
31
Using Constructors



Chapter 5
Always use a constructor after new
For example, using the Account class, we did the following:
Account myAcct = new Account(acctNum,pin,bal,rate);
» this calls the Account constructor with String, String, double,
double parameters
If you want to change values of instance variables after you have
created an object, you must use other methods for the object
» you cannot call a constructor for an object after it is created
– myAcct.Account(acctNum,pin,bal,rate); // would be illegal
» set methods should be provided for this purpose
Java: an Introduction to Computer Science & Programming - Walter Savitch
33
Oh, about Objects / References

Chapter 5
A constructor returns a reference to an object – that is, the memory
address
Account myAcct = new Account(); // returns the address of the object
// hence myAcct really is a reference to the object and not
// the actual object
Java: an Introduction to Computer Science & Programming - Walter Savitch
34