Download Chapter 7: Class Variables and Methods Java Programming

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Chapter 7: Class Variables and Methods
Chapter 7
Class Variables and Methods
Java Programming
FROM THE BEGINNING
1
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
7.1 Class Methods
Versus Instance Methods
• An instance method can be used only after the object is
created. The instance variable can be accessed by the
object as well.
Example:
Account acct = new Account(100.0);
Acct.deposit(200.0);
• Methods that don’t need access to instance variables are
known as class methods (or static methods.)
Example:
SimpleIO.prompt, SimpleIO.readLine,
Convert.toDouble, Integer.parseInt, Math.abs
Math.max, Math.min, Math.pow, Math.round,
Math.sqrt
Java Programming
FROM THE BEGINNING
2
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
Class Methods
• Uses of class methods:
– To provide a service to other classes. Methods in this
category are declared public.
– To help other methods in the same class. “Helper”
methods provide assistance to other methods in the
same class. Helper methods should be private.
– To provide access to hidden class variables. If a class
variable is private, the only way for a method in a
different class to access the variable or to change its
value is to call a class method that has permission to
access the variable. Methods in this category are
declared public.
Java Programming
FROM THE BEGINNING
3
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
Class Methods
• Class methods have another important purpose: to
specify where a program begins execution. 
main is a class method, so every Java application
has at least one class method.
• A class from which objects can be created is said
to be instantiable. For example the Math class is
not instantiable.
Java Programming
FROM THE BEGINNING
4
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
Summary
Instance Methods
• Perform an operation
on an object.
• Are called by an
object.
• Have access to
instance variables
inside the calling
object.
Java Programming
FROM THE BEGINNING
Class Methods
• Do not perform an
operation on an object.
• Are not called by an
object.
• Do not have access to
instance variables.
5
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
7.2 Writing Class Methods
• The declaration of a class method must contain the
word static.
Java Programming
FROM THE BEGINNING
6
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
Access Modifiers for Class Methods
• Class methods that are intended for use by other
classes should be declared public.
Example: Math.round
• Class methods that are intended for use within a
single class should be declared private.
• A modification of private method does not
affect other classes.
Java Programming
FROM THE BEGINNING
7
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
7.3 The return Statement
• When a method has a result type other than void,
a return statement must be used to specify what
value the method returns.
• Form of the return statement:
return expression ;
• The expression is often just a literal or a variable:
return 0;
return n;
• Expressions containing operators are also allowed:
return x * x - 2 * x + 1;
Java Programming
FROM THE BEGINNING
8
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
A Common Error
• When a method returns a result, make sure that
there’s no way to leave the method without
executing a return statement.
• The following method body is illegal, because the
method returns nothing if n is equal to 0:
if (n > 0)
return +1;
else if (n < 0)
return -1;
Java Programming
FROM THE BEGINNING
9
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
Example: A Dollar-Formatting Method
• Display amounts to dollars.cents.
• System.out.println won’t always provide
the desired formatting:
Example : 10.50  10.5
10000000.00  1.0E7.
• Also, amounts won’t be rounded to cents, so
values such as 10.50001 may be printed.
Java Programming
FROM THE BEGINNING
10
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
Example: A Dollar-Formatting Method
• A class method that implements this strategy:
private static String formatAsMoney(double amount) {
//round the amount first
long roundedAmount = Math.round(amount * 100);
long dollars = roundedAmount / 100;
long cents = roundedAmount % 100;
String result;
if (cents <= 9)
result = dollars + ".0" + cents;
else
result = dollars + "." + cents;
return result;
}
Java Programming
FROM THE BEGINNING
11
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
Conditional Expressions
• The two return statements in the
formatAsMoney method are nearly identical:
if (cents <= 9)
return dollars + ".0" + cents;
else
return dollars + "." + cents;
This suggests that there might be a way to
simplify the code.
• Java’s conditional operator is often handy in such
situations.
Java Programming
FROM THE BEGINNING
12
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
Conditional Expressions
expr1 ? expr2 : expr3
• “if expr1 then expr2 else expr3.”
The resulting expression is said to be a conditional
expression.
• The conditional operator is a ternary operator, because it
requires three operands.
• The conditional operator has lower precedence than all
other operators except the assignment operators.
Java Programming
FROM THE BEGINNING
13
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
Conditional Expressions
String result;
if (cents <= 9)
result = dollars + ".0" + cents;
else
result = dollars + "." + cents;
return result;
• To:
return (cents <= 9) ? (dollars + ".0" + cents) :
(dollars + "." + cents);
• Or:
return dollars + (cents <= 9 ? ".0" : ".") +
cents;
Java Programming
FROM THE BEGINNING
14
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
Conditional Expressions
• The conditional operator isn’t used much in Java except
in return statements.
• Conditional expressions occasionally appear in calls of
System.out.print or System.out.println.
• The statement
if (isLeapYear)
System.out.println("February has 29 days");
else
System.out.println("February has 28 days");
could be written as
System.out.println("February has " +
(isLeapYear ? 29 : 28) +
" days");
Copyright © 2000 W. W. Norton & Company.
15
Java Programming
All rights reserved.
FROM THE BEGINNING
Chapter 7: Class Variables and Methods
Conditional Expressions
• A conditional expression can be used just like any
other kind of expression.
• For example, a conditional expression can appear
on the right side of an assignment:
int
int
int
int
i
j
m
n
=
=
=
=
1;
2;
i > j ? i : j;
(i >= 0 ? i : 0) + j;
Java Programming
FROM THE BEGINNING
16
// m is 2
// n is 3
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
7.4 Parameters
• How Arguments Are Passed.
– by value : copies of arguments are passed by
value.
• Primitive type. The value of the argument is
copied into the corresponding parameter.
• Reference type. The value of the argument—
a reference—is copied into the parameter.
– What happens when we change the value of a
parameter?
Java Programming
FROM THE BEGINNING
17
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
How Arguments Are Passed
• Example 1: Assigning a new value to a parameter.
private static void printStars(int numStars) {
while (numStars-- > 0)
System.out.print('*');
System.out.println();
}
• An example in which printStars is called:
int n = 30;
System.out.println("Value of n before call: " + n);
printStars(n);
System.out.println("Value of n after call: " + n);
• The output produced by these statements:
Value of n before call: 30
******************************
Value of n after call: 30
Java Programming
FROM THE BEGINNING
18
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
How Arguments Are Passed
• An example in which printStars is called:
int n = 30;
System.out.println("Value of n before call: " + n);
printStars(n);
System.out.println("Value of n after call: " + n);
• The output produced by these statements:
Value of n before call: 30
******************************
Value of n after call: 30
Java Programming
FROM THE BEGINNING
19
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
How Arguments Are Passed
• When printStars was called, the value of n was
copied into the numStars parameter:
• At the end of the method call, n is not changed.
Java Programming
FROM THE BEGINNING
20
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
How Arguments Are Passed
• Example 2: Modifying an object passed as an argument.
private static void transferBalance(
Account oldAccount, Account newAccount) {
newAccount.deposit(oldAccount.getBalance());
oldAccount.close(); }
Java Programming
FROM THE BEGINNING
21
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
How Arguments Are Passed
• An example in which transferBalance is called:
Account acct1 = new Account(1000.00);
Account acct2 = new Account(500.00);
System.out.println(acct1.getBalance()” : “ +
acct2.getBalance());
transferBalance(acct1, acct2);
System.out.println(acct1.getBalance()” : “ +
acct2.getBalance());
• The output produced by these statements:
1000.00 : 500.00
0.00 : 1500.00
Java Programming
FROM THE BEGINNING
22
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
How Arguments Are Passed
Account acct1 = new Account(1000.00);
Account acct2 = new Account(500.00);
Java Programming
FROM THE BEGINNING
23
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
How Arguments Are Passed
• If we call:
transferBalance(acct1, acct2);
Java Programming
FROM THE BEGINNING
24
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
How Arguments Are Passed
• As a result of calling transferBalance, the
state of the acct1 and acct2 objects is changed:
Java Programming
FROM THE BEGINNING
25
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
Array Parameters
• Passing arrays to methods is much like passing objects.
• When an array is passed to a method, only a reference to
the array is copied. As a result:
1. Passing an array to a method takes very little time.
2. A method can modify the elements of any array passed to
it.
Java Programming
FROM THE BEGINNING
26
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
Array Parameters
Example:
private static void setElementsToZero(int[] a) {
for (int i = 0; i < a.length; i++)
a[i] = 0;
}
========================================
int [] anArray = new int [10];
For (int i=0;i<anArray.length; i++) anArray[i]=i;
System.out.println(anArray[3]);
setElementsToZero(anArray);
System.out.println(anArray[3]);
The output produced by these statements:
3
0
Java Programming
FROM THE BEGINNING
27
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
Program Arguments
• program arguments (or command-line
arguments) : any data supplied by the user on the
command line
• How to use program arguments?
• After compiling, in command line:
java MyProgram
java MyProgram 100 200
Java Programming
FROM THE BEGINNING
28
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
Program Arguments
• How to write a program that accesses commandline arguments supplied by the user?
• In the main method :
public static void main(String[] args) {
…
}
• In the example, java MyProgram 100 200
args[0] = “100”, args[1]=200.
Java Programming
FROM THE BEGINNING
29
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
Program Arguments
• Some programs have switches or options that can
be specified on the command line to affect the
program’s behavior.
• These usually begin with a distinctive character,
such as - or /.
• javac has a -O option, which causes it to
“optimize” a program for better performance:
javac -O MyProgram.java
Java Programming
FROM THE BEGINNING
30
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
Program Arguments
• The main method’s parameter doesn’t have to be
named args ( “arguments”). You can change to
any.
• The square brackets can go after args if desired:
public static void main(String argv[]) {
…
}
• Typically, a program will use a loop to examine
and process the command-line arguments.
Java Programming
FROM THE BEGINNING
31
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
Program: Printing Command-Line Arguments
• A program that prints each command-line
argument on a line by itself:
PrintArgs.java
// Prints command-line arguments on separate lines
public class PrintArgs {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++)
System.out.println(args[i]);
}
}
Java Programming
FROM THE BEGINNING
32
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
7.5 Class Variables
• Class variables: Variables that belong to a class,
but not to any particular instance of a class.
• Called static variables or static fields as well.
• Class variables are stored only once in the entire
program.
Java Programming
FROM THE BEGINNING
33
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
Declaring Class Variables
• In declarations of class variables, static is
inserted :
public static int numAccounts;
private static int windowHeight;
• Variables that are declared public are accessible
outside the class.
• Variables that are declared private are hidden
inside the class.
Java Programming
FROM THE BEGINNING
34
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
Using Class Variables
• Outside of the class: Class-name.variable-name.
Example:
int accountsOpen = Account.numAccounts;
• Within the class, a class variable can be accessed
directly, without a class name or dot:
numAccounts++;
• A private class variable can be accessed only within
its own class, so the class name and dot aren’t needed:
windowHeight = 200;
Java Programming
FROM THE BEGINNING
35
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
Uses for Class Variables
• Common uses for class variables:
– As global variables. (A global variable is a variable that
can be used by any method in any class.)
– As constants.
– To store data for class methods.
Java Programming
FROM THE BEGINNING
36
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
Using Class Variables
as Global Variables
• Only way to use global variables: a variable
should be declared to be a public class variable.
• Avoid global variables, though.
Global variables make programs harder to test and
harder to modify. Can make many mistakes.
Java Programming
FROM THE BEGINNING
37
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
Class Variables in the System Class
• Example
System.out.println
• The System class has three class variables: in, out, and
err. Each variable represents a stream—a source of input
or a destination for output.
public static PrintStream out, err;
Public static InputStream in;
• Accessed by System.in, System.out, and
System.err.
Java Programming
FROM THE BEGINNING
38
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
The PrintStream Class
• PrintStream class provides the print and println
methods.
• Example:
System.out.println("Java rules!");
• System.out is a class variable that represents an
instance of the PrintStream class.
• This object is invoking println, one of the instance
methods in the PrintStream class.
Java Programming
FROM THE BEGINNING
39
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
Class Variables in the System Class
• System.in represents the standard input stream.
By default, it is attached to the user’s keyboard.
• System.out represents the standard output stream.
By default, it is displayed in the window
• System.err represents the standard error stream.
By default, it is displayed in the same window as data
written to System.out.
Java Programming
FROM THE BEGINNING
40
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
Redirecting the Standard Streams
• From a file instead of from the keyboard:
java MyProgram <myInputFile
• The output of a program can also be sent to a file:
java MyProgram >myOutputFile
• Read from one file and write to another:
java MyProgram <myInputFile >myOutputFile
• If redirects, error messages written to System.out won’t
appear on the screen.
• But, error messages written to System.err will still
appear on the screen.
Java Programming
FROM THE BEGINNING
41
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
Using Class Variables as Constants
• Use final for a constant class variable.
• Example:
public class Math {
public static final double E =
2.7182818284590452354;
public static final double PI =
3.14159265358979323846;
…
}
• E and PI are accessed by writing Math.E and Math.PI.
• Other examples of class variables used as constants:
– Color.white, Color.black, ...
– Font.PLAIN, Font.BOLD, Font.ITALIC
Java Programming
FROM THE BEGINNING
42
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
Using Class Variables as Constants
• Other examples of class variables used as constants:
– Color.white, Color.black, ...
– Font.PLAIN, Font.BOLD, Font.ITALIC
• Most API classes follow the convention of using all
uppercase letters for names of constants.
• Like all class variables, constants can be declared
public or private.
• Constants that are to be used by other classes must
be declared public.
Java Programming
FROM THE BEGINNING
43
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
Using Class Variables to
Store Data for Class Methods
• When a method returns, its local variables no
longer exist.
• If a class method needs to store data where it will
be safe after the method returns, it must use a class
variable instead of a local variable.
• Class variables are also used for sharing data
among class methods in a class.
• Class variables that store data for class methods
should be declared private.
Java Programming
FROM THE BEGINNING
44
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
Summary
Instance Variables
• Declared in a
class.
• Created when an
instance of the
class is created.
• Retain values as
long as object
exists.
• Access
controlled by
public and
private.
Java Programming
FROM THE BEGINNING
•
•
•
•
Class Variables
Declared in a
class.
Created when
program begins
to execute.
Retain values
until program
terminates.
Access
controlled by
public and
private.
45
Local Variables
• Declared in a
method.
• Created when
method is called.
• Retain values
until method
returns.
• Access limited to
method in which
declared.
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
7.6 Adding Class Variables
and Methods to a Class
• The outline of a program that contains class
variables and class methods:
public class class-name {
declarations of class variables (use static)
public static void main(String[] args) {
…
}
declarations of class methods (use static)
}
• Java doesn’t require that class variables and
methods go in any particular order.
Java Programming
FROM THE BEGINNING
46
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
7.7 Writing Helper Methods
• Instead of putting all the code for a program into
main, it’s better to delegate some of its duties to
helper methods. – functions inside of a method.
• A helper method is to assist another method, not
necessarily main.
• Helper methods have two primary advantages:
– Greater clarity. The main method can be shortened, with helper
methods taking care of details.
– Less redundancy. A repeated segment of code can be moved into a
method and then called as many times as needed.
Java Programming
FROM THE BEGINNING
47
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
7.8 Designing Methods
• Issues that arise in the design of methods:
– When is a method needed?
– What should the name of the method be?
– What parameters will it need?
Java Programming
FROM THE BEGINNING
48
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
Chapter 7: Class Variables and Methods
Designing Methods
• Consider..
– Cohesion: a method should perform a single, clearly
defined task.
– Stepwise refinement: dividing larger methods into
smaller ones.  use helper methods.
– Choosing method names wisely: easily understandable.
– Parameters or class variables?
– Return type
Java Programming
FROM THE BEGINNING
49
Copyright © 2000 W. W. Norton & Company.
All rights reserved.