public class PlayCircle

Download Report

Transcript public class PlayCircle

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
The "this." Operator




this. refers to the object that contains the reference
Methods called in an object definition file do not need to reference itself
You may either use "this.", or omit it, since it is presumed
For example, if answerOne() is a method defined in the class Oracle:
public class Oracle
{
...
//One way to invoke the answerOne method defined
//in this file: this.answerOne();
//Another way is to omit "this."
answerOne(); //"this." is presumed
...
}
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
2
When an Object Is Required


Chapter 5
Methods called outside the object definition require an object to
precede the method name
For example:
Oracle myOracle = new Oracle();
//myOracle is not part of the definition code
//for Oracle
...
//dialog is a method defined in Oracle class
myOracle.dialog();
...
Java: an Introduction to Computer Science & Programming - Walter Savitch
3
Static Methods




Chapter 5
Some methods do work but do not need an object
» For example, methods to calculate area:
just pass the required parameters and return the
area
Use the class name instead of an object name to
invoke them
For example
» CircleFirstTry is a class with methods to
perform calculations on circles:
CircleFirstTry.area(myRadius);
» Notice that the the method invocation uses
"className." instead of " circleObject."
Also called class methods
Java: an Introduction to Computer Science & Programming - Walter Savitch
4
Static Methods
Declare static methods with the static modifier, for
example:
public static double area(double radius)
...



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
5
public class PlayCircle
{
public static final double
PI = 3.141592;
private double diameter;
Display 5.5 PlayCircle
public void setDiameter(double newDiameter)
{
diameter = newDiameter;
}
public static double area(double radius)
{
return (PI*radius*radius);
}
public void showArea()
{
System.out.println("Area is " + area(diameter/2));
}
public static void areaDialog()
{
System.out.println("Enter diameter of circle:");
double newDiameter = SavitchIn.readLineDouble();
PlayCircle c = new PlayCircle();
c.setDiameter(newDiameter);
c.showArea();
}
}
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
6
Display 5.6 PlayCircleDemo
public class PlayCircleDemo
{
public static void main(String[] args)
{
PlayCircle circle = new PlayCircle();
circle.setDiameter(2);
System.out.println("If circle has diameter 2, ");
circle.showArea();
System.out.println("Now, you choose the diameter:");
PlayCircle.areaDialog();
}
}
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
7
Execution Result of
PlayCircleDemo
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
8
Uses for Static Methods


Static methods are commonly used to provide libraries of useful
and related functions
Examples:
» the Math class
– automatically provided with Java
– functions include pow, sqrt, max, min, etc.
– see the next slide for more details
» SavitchIn defines methods for keyboard input
– not automatically provided with Java
– functions include readLineInt, readLineDouble,
etc.
– see the appendix
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
9
The Math Class (1/2)
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 whole numbers (although they are type double)
» Math.round returns the whole number nearest its argument
Math.round(3.3) returns 3.0 and Math.round(3.7) returns 4.0
» 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

Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
10
The Math Class (2/2)

Math.pow(2.0, 3.0) returns 8.0.

Math.abs(-7) returns 7.

Math.max(5, 6) returns 6.

Math.min(5, 6) returns 5.

Math.sqrt(4.0) returns 2.0.
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
11
Static Variables

The StaticDemo program in the text uses a static variable:
private static int numberOfInvocations = 0;

Similar to definition of a named constant, which is a special case
of static variables.
May be public or private but are usually private for the same
reasons instance variables are.
Only one copy of a static variable and it can be accessed by any
object of the class.
May be initialized (as in example above) or not.
Can be used to let objects of the same class coordinate.
Not used in the rest of the text.





Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
12
Wrapper Classes



Chapter 5
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
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
13
Wrapper class example: Integer



Chapter 5
Declare an Integer class variable:
Integer n = new Integer();
Convert the value of an Integer variable to its
primitive type, int:
int i = n.intValue();//intValue returns
an int
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
Java: an Introduction to Computer Science & Programming - Walter Savitch
14
Wrapper class example: Integer

Some useful Integer methods:
» Integer.valueOf("123") to convert a string
of numerals to an integer
» Integer.toString(123) to convert an
Integer to a String

The other wrapper classes have similar constants
and functions
See the text for useful methods for the class
Character

Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
15
Wrapper class example: Character




toUpperCase()
- Both Character.toUpperCase(‘a’) and Character.toUpperCase(‘A’)
return ‘A’.
toLowerCase()
- Both Character.toLowerCase(‘A’) and Character.toLowerCase(‘a’)
return ‘a’.
isUpperCase()
- Character.isUpperCase(‘A’) returns true.
- Character.isUpperCase(‘a’) returns false.
isWhitespace()
- Character.isWhitespace(‘ ‘) returns ture.
- Character.isWhitespace(‘A’) returns false.
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
16
Wrapper class example: Character
Chapter 5

isLetter()
- Character.isLetter(‘A’) returns true.
- Character.isLetter(‘%’) returns false.

isDigit()
- Character.isDigit(‘5’) returns true.
- Character.isDigit(‘A’) returns false.
Java: an Introduction to Computer Science & Programming - Walter Savitch
17
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
18
Designing Methods:
Top-Down Design






Chapter 5
In pseudocode, write a list of subtasks that the method must do.
If you can easily write Java statements for a subtask, you are
finished with that subtask.
If you cannot easily write Java statements for a subtask, treat it
as a new problem and break it up into a list of subtasks.
Eventually, all of the subtasks will be small enough to easily
design and code.
Solutions to subtasks might be implemented as private helper
methods.
Top-down design is also known as divide-and-conquer or
stepwise refinement.
Java: an Introduction to Computer Science & Programming - Walter Savitch
19
Programming Tips for
Writing Methods

Apply the principle of encapsulation and detail hiding by using the
public and private modifiers judiciously
» If the user will need the method, make it part of the interface
by declaring it public
» If the method is used only within the class definition (a helper
method, then declare it private

Chapter 5
Create a main method with diagnostic (test) code within a class's
definition
» run just the class to execute the diagnostic program
» when the class is used by another program the class's main
is ignored
Java: an Introduction to Computer Science & Programming - Walter Savitch
20
Testing a Method





Chapter 5
Test programs are sometimes called driver programs
Keep it simple: test only one new method at a time
» driver program should have only one untested method
If method A uses method B, there are two approaches:
Bottom up
» test method B fully before testing A
Top down
» test method A and use a stub for method B
» A stub is a method that stands in for the final version and
does little actual work. It usually does something as trivial as
printing a message or returning a fixed value. The idea is to
have it so simple you are nearly certain it will work.
Java: an Introduction to Computer Science & Programming - Walter Savitch
21
Overloading


Chapter 5
The same method name has more than one definition
within the same class
Each definition must have a different signature
» 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
Java: an Introduction to Computer Science & Programming - Walter Savitch
22
Signature




the combination of method name and number and types of
arguments, in order
equals(Species) has a different signature than
equals(String)
» same method name, different argument types
myMethod(1) has a different signature than myMethod(1, 2)
» same method name, different number of arguments
myMethod(10, 1.2) has a different signature than
myMethod(1.2, 10)
» same method name and number of arguments, but different
order of argument types
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
23
public class Statistician
Display 5.15
{
public static void main(String[] args)
Overloading
{
double average1 = Statistician.average(40.0, 50.0);
double average2 = Statistician.average(1.0, 2.0, 3.0);
char average3 = Statistician.average('a', 'c');
System.out.println("average1 = " + average1);
System.out.println("average2 = " + average2);
System.out.println("average3 = " + average3);
}
public static double average(double first, double second)
{
return ((first + second)/2.0);
}
public static double average(double first,
double second, double third)
{
return ((first + second + third)/3.0);
}
public static char average(char first, char second)
{
return (char)(((int)first + (int)second)/2);
}
}
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
24
Execution Result of
Statistician.java
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
25
Gotcha: Overloading and Argument Type

Accidentally using the wrong datatype as an argument can
invoke a different method

For example, see the Pet class in the text
» set(int) sets the pet's age
» set(double) sets the pet's weight
» You want to set the pet's weight to 6 pounds:
– set(6.0) works as you want because the argument is
type double
– set(6) will set the age to 6, not the weight, since the
argument is type int
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
26
Gotcha: Automatic Type Conversion
and Overloading

If Java does not find a signature match, it attempts some automatic type
conversions, e.g. int to double

An unwanted version of the method may execute
In the text Pet example of overloading:
What you want: name "Cha Cha", weight 2, and age 3
But you make two mistakes:
1. you reverse the age and weight numbers, and
2. you fail to make the weight a type double.
» set("Cha Cha", 2, 3) does not do what you want

– it sets the pet's age = 2 and the weight = 3.0
» Why?
– set has no definition with the argument types String, int, int
– However, it does have a definition with String, int, double,
so it promotes the last number, 3, to 3.0 and executes the method
with that signature
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
27
Display 5.16
Pet class (1/4)
public class Pet
{
private String name;
private int age;//in years
private double weight;//in pounds
public static void main(String[] args)
{
Pet myDog = new Pet();
myDog.set("Fido", 2, 5.5);
myDog.writeOutput();
System.out.println("Changing name.");
myDog.set("Rex");
myDog.writeOutput();
System.out.println("Changing weight.");
myDog.set(6.5);
myDog.writeOutput();
System.out.println("Changing age.");
myDog.set(3);
myDog.writeOutput();
}
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
28
Display 5.16
Pet class (2/4)
public void writeOutput()
{
System.out.println("Name: " + name);
System.out.println("Age: " + age + " years");
System.out.println("Weight: " + weight + " pounds");
}
public void set(String newName)
{
name = newName;
//age and weight are unchanged.
}
public void set(int newAge)
{
if (newAge <= 0)
{
System.out.println("Error: illegal age.");
System.exit(0);
}
else
age = newAge;
//name and weight are unchanged.
}
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
29
public void set(double newWeight)
{
if (newWeight <= 0)
{
System.out.println("Error: illegal weight.");
System.exit(0);
}
else
weight = newWeight;
//name and age are unchanged.
}
public void set(String newName, int newAge, double newWeight)
{
name = newName;
if ((newAge <= 0) || (newWeight <= 0))
{
System.out.println("Error: illegal age or weight.");
System.exit(0);
}
else
{
age = newAge;
weight = newWeight;
}
}
Display 5.16
Pet class (3/4)
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
30
public String getName()
{
return name;
}
Display 5.16
Pet class (4/4)
public int getAge()
{
return age;
}
public double getWeight()
{
return weight;
}
}
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
31
Execution Result of
Pet.java
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
32
public class Money
{
private long dollars;
private long cents;
Display 5.17
Money class (1/5)
public void set(long newDollars)
{
if (newDollars < 0)
{
System.out.println(
"Error: Negative amounts of money are not allowed.");
System.exit(0);
}
else
{
dollars = newDollars;
cents = 0;
}
}
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
33
public void set(double amount)
Display 5.17
{
Money class (2/5)
if (amount < 0)
{
System.out.println(
"Error: Negative amounts of money are not allowed.");
System.exit(0);
}
else
{
long allCents = Math.round(amount*100);
dollars = allCents/100;
cents = allCents%100;
}
}
public void set(Money otherObject)
{
this.dollars = otherObject.dollars;
this.cents = otherObject.cents;
}
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
34
public void set(String amountString)
{
String dollarsString;
String centsString;
if (amountString.charAt(0) == '$')
amountString = amountString.substring(1);
amountString = amountString.trim();
int pointLocation = amountString.indexOf(".");
if (pointLocation < 0) //If no decimal point
{
cents = 0;
dollars = Long.parseLong(amountString);
}
else//String has a decimal point.
{
dollarsString = amountString.substring(0, pointLocation);
centsString = amountString.substring(pointLocation + 1);
if (centsString.length() <= 1)
centsString = centsString + "0";
dollars = Long.parseLong(dollarsString);
cents = Long.parseLong(centsString);
if ((dollars < 0) || (cents < 0) || (cents > 99))
{
System.out.println(
"Error: Illegal representation of money amount.");
System.exit(0);
}
}
}
Display 5.17
Money class (3/5)
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
35
Display 5.17
Money class (4/5)
public void readInput()
{
System.out.println("Enter amount on a line by itself:");
String amount = SavitchIn.readLine();
set(amount.trim());
}
public void writeOutput()
{
System.out.print("$" + dollars);
if (cents < 10)
System.out.print(".0" + cents);
else
System.out.print("." + cents);
}
public Money times(int n)
{
Money product = new Money();
product.cents = n*cents;
long carryDollars = product.cents/100;
product.cents = product.cents%100;
product.dollars = n*dollars + carryDollars;
return product;
}
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
36
Display 5.17
Money class (5/5)
public Money add(Money otherAmount)
{
Money sum = new Money();
sum.cents = this.cents + otherAmount.cents;
long carryDollars = sum.cents/100;
sum.cents = sum.cents%100;
sum.dollars = this.dollars
+ otherAmount.dollars + carryDollars;
return sum;
}
}
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
37
public class MoneyDemo
{
public static void main(String[] args)
{
Money start = new Money();
Money goal = new Money();
Display 5.18
Using Money class
System.out.println("Enter your current savings:");
start.readInput();
goal = start.times(2);
System.out.print(
"If you double that, you will have ");
goal.writeOutput();
System.out.println(", or better yet:");
goal = start.add(goal);
System.out.println(
"If you triple that original amount, you will have:");
goal.writeOutput();
System.out.println();
System.out.println(
"Remember: A penny saved");
System.out.println("is a penny earned.");
}
}
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
38
Execution Result of
MoneyDemo.java
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
39
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
40
Defining Constructors

Constructor headings do not include the word void

In fact, 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
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
41
Constructor Example from
PetRecord
public class PetRecord
{
private String name;
private int age; //in years
private double weight; //in pounds
. . .
public PetRecord(String initialName)
{
Initializes three instance
name = initialName;
variables: name from the
parameter and age and weight
age = 0;
with default initial values.
weight = 0;
}
Sample use:
PetRecord pet1 = new Pet(“Eric”);
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
42
public class PetRecord
{
private String name;
private int age;//in years
private double weight;//in pounds
public void writeOutput()
{
System.out.println("Name: " + name);
System.out.println("Age: " + age + " years");
System.out.println("Weight: " + weight + " pounds");
}
public PetRecord(String initialName, int initialAge,
double initialWeight)
{
name = initialName;
if ((initialAge < 0) || (initialWeight < 0))
{
System.out.println("Error: Negative age or weight.");
System.exit(0);
}
else
{
age = initialAge;
weight = initialWeight;
}
}
Display 5.19
Pet class
With Constructors
(1/5)
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
43
Display 5.19
PetRecord class
(2/5)
public void set(String newName,
int newAge, double newWeight)
{
name = newName;
if ((newAge < 0) || (newWeight < 0))
{
System.out.println("Error: Negative age or weight.");
System.exit(0);
}
else
{
age = newAge;
weight = newWeight;
}
}
public PetRecord(String initialName)
{
name = initialName;
age = 0;
weight = 0;
}
public void set(String newName)
{
name = newName; //age and weight are unchanged.
}
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
44
public PetRecord(int initialAge)
Display 5.19
{
PetRecord class
name = "No name yet.";
weight = 0;
(3/5)
if (initialAge < 0)
{
System.out.println("Error: Negative age.");
System.exit(0);
}
else
age = initialAge;
}
public void set(int newAge)
{
if (newAge < 0)
{
System.out.println("Error: Negative age.");
System.exit(0);
}
else
age = newAge;
//name and weight are unchanged.
}
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
45
public PetRecord(double initialWeight)
Display 5.19
{
PetRecord class
name = "No name yet";
age = 0;
(4/5)
if (initialWeight < 0)
{
System.out.println("Error: Negative weight.");
System.exit(0);
}
else
weight = initialWeight;
}
public void set(double newWeight)
{
if (newWeight < 0)
{
System.out.println("Error: Negative weight.");
System.exit(0);
}
else
weight = newWeight; //name and age are unchanged.
}
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
46
public PetRecord()
// Default constructor
{
name = "No name yet.";
age = 0;
weight = 0;
}
Display 5.19
PetRecord class
(5/5)
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public double getWeight()
{
return weight;
}
}
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
47
Using Constructors



Chapter 5
Always use a constructor after new
For example, using the Pet class in text:
Pet myCat = new Pet("Calvin", 5, 10.5);
» this calls the Pet constructor with String, int, 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
» set methods should be provided for this purpose
Java: an Introduction to Computer Science & Programming - Walter Savitch
48
Display 5.20
Using constructors
public class PetRecordDemo
{
public static void main(String[] args)
{
PetRecord usersPet = new PetRecord("Jane Doe");
System.out.println("My records on your pet are
inaccurate.");
System.out.println("Here is what they currently say.");
usersPet.writeOutput();
System.out.println("Please enter the correct pet name:");
String correctName = SavitchIn.readLine();
System.out.println("Please enter the correct pet age:");
int correctAge = SavitchIn.readLineInt();
System.out.println("Please enter the correct pet weight:");
double correctWeight = SavitchIn.readLineDouble();
usersPet.set(correctName, correctAge, correctWeight);
System.out.println("My updated records now say:");
usersPet.writeOutput();
}
}
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
49
Execution Result of
PetRecordDemo.java
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
50
Constructor Returning a Reference
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
51
Information Hiding Revisited




Chapter 5
Using instance variables of a class type takes special care
The details are beyond the scope of this text, but
» the problem in described in section 5.4/page275
» Appendix 6 covers some of the details
The problem stems from the fact that, unlike primitive types,
object identifiers contain the object's address, not its value
» returning an object gives back the address, so the called
method has direct access to the calling object
» the calling object is "unprotected" (usually undesirable)
» best solution: cloning, but that is beyond the scope of this
book
One solution: stick to returning primitive types (int, char,
double, boolean, etc.) or String
Java: an Introduction to Computer Science & Programming - Walter Savitch
52
public class CadetClass
{
private PetRecord pet;
Display 5.22
Insecure class
public CadetClass()
{
pet =
new PetRecord("Faithful Guard Dog", 5, 75);
}
public void writeOutput()
{
System.out.println("Here's the pet:");
pet.writeOutput();
}
public PetRecord getPet()
{
return pet;
}
}
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
53
Display 5.23
Changing private data
public class Hacker
{
public static void main(String[] args)
{
CadetClass starFleetOfficer = new CadetClass();
System.out.println("starFleetOfficer contains:");
starFleetOfficer.writeOutput();
PetRecord badGuy;
badGuy = starFleetOfficer.getPet();
badGuy.set("Dominion Spy", 1200, 500);
System.out.println("Looks like a security breach:");
System.out.println("starFleetOfficer now contains:");
starFleetOfficer.writeOutput();
System.out.println("The pet wasn't so private!");
}
}
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
54
Execution Result of
Hacker.java
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
55
Packages
Chapter 5

A way of grouping and naming a collection of related classes
» they serve as a library of classes
» they do not have to be in the same directory as your
program

The first line of each class in the package must be
the keyword package followed by the name of the package:
package mystuff.utilities;

To use classes from a package in a program put an import
statement at the start of the file:
import mystuff.utilities.*;
» note the ".*" notation
Java: an Introduction to Computer Science & Programming - Walter Savitch
56
Package Naming Conventions



Chapter 5
Use lowercase
The name is the file pathname with subdirectory
separators ("\" or "/", depending on your system)
replaced by dots
For example, if the package is in a file named
"utilities" in directory "mystuff", the package name is:
mystuff.utilities
Java: an Introduction to Computer Science & Programming - Walter Savitch
57
Package Naming Conventions

Pathnames are usually relative and use the
CLASSPATH environment variable

For example, if:
CLASSPATH=c:jdk\lib\mystuff, and your file
utilities is in c:jdk\lib\mystuff, then you
would use the name:
utilities
» the system would look in directory
c:jdk\lib\mystuff and find the utilities
package
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
58
Summary
Part 1




Chapter 5
A method definition can use a call to another method
of the same class
static methods can be invoked using the class name
or an object name
Top-down design method simplifies program
development by breaking a task into smaller pieces
Test every method in a program in which it is the only
untested method
Java: an Introduction to Computer Science & Programming - Walter Savitch
59
Summary
Part 2



Each primitive type has a corresponding wrapper
class
Overloading: a method has more than one definition
in the same class (but the number of arguments or
the sequence of their data types is different)
» one form of polymorphism
Constructor: a method called when an object is
created (using new)
» default constructor: a constructor with no
parameters
Chapter 5
Java: an Introduction to Computer Science & Programming - Walter Savitch
60