Document 7685547
Download
Report
Transcript Document 7685547
Chapter 4
Defining Instantiable Classes
5/25/2016
Introduction to Object-Oriented Programming with Java--Wu
Chapter 4 - 1
Chapter 4 Objectives
After you have read and studied this chapter, you
should be able to
Define an instantiable class with multiple methods and a
constructor.
Differentiate the local and instance variables.
Define and use value-returning methods.
Distinguish private and public methods.
Distinguish private and public data members.
Describe how the arguments are passed to the
parameters in method definitions.
Use System.out for temporary output to verify the
program code.
5/25/2016
Introduction to Object-Oriented Programming with Java--Wu
Chapter 4 - 2
Building Large Programs
Learning how to define instantiable classes is the first step
toward mastering the skills necessary in building large programs.
A class is instantiable if we can create instances of the class.
The MainWindow, InputBox, and OutputBox classes are all
instantiable classes while the Math class is not.
In this chapter you will learn how to define instantiable classes
and different types of methods included in the instantiable
classes.
5/25/2016
Introduction to Object-Oriented Programming with Java--Wu
Chapter 4 - 3
CurrencyConverter
Let’s start with an example to cover the basics of
defining instantiable classes.
In designing an instantiable class, we start with its
specification, namely, how we want the class and its
instances behave.
A CurrencyConverter object will perform a conversion
from a foreign currency and the U.S. dollar.
What would be the most natural way for us to
interact with CurrencyConverter objects?
5/25/2016
Introduction to Object-Oriented Programming with Java--Wu
Chapter 4 - 4
fromDollar and toDollar Methods
We would like to have (at least) two methods for
conversion: fromDollar and toDollar.
CurrencyConverter
yenConverter
yenConverter;
= new CurrencyConverter;
double amountInYen
= yenConverter.fromDollar( 500);
double amountInUS
= yenConverter.toDollar(15000);
5/25/2016
Introduction to Object-Oriented Programming with Java--Wu
Converting
$500 US to yen.
Converting
15,000 yen to
US dollar.
Chapter 4 - 5
setExchangeRate Methods
Since the exchange rate fluctuates, we need a
method to set the exchange rate.
CurrencyConverter
yenConverter
yenConverter;
= new CurrencyConverter;
yenConverter.setExchangeRate( 106.55);
$1.00 US = 106.55 yen
5/25/2016
Introduction to Object-Oriented Programming with Java--Wu
Chapter 4 - 6
Using Multiple Instances
Once the CurrencyConverter class is defined, we can
use its multiple instances.
CurrencyConverter
yenConverter, markConverter;
double
amountInYen, amountInMark, amountInDollar;
yenConverter
= new CurrencyConverter();
yenConverter.setExchangeRate(130.77);
markConverter = new CurrencyConverter( );
markConverter.setExchangeRate(1.792);
5/25/2016
amountInYen
= yenConverter.fromDollar( 200 );
amountInMark
= markConverter.fromDollar( 200 );
amountInDollar
= yenConverter.toDollar( 10000 );
amountInMark
= markConverter.fromDollar(amountInDollar);
Introduction to Object-Oriented Programming with Java--Wu
Chapter 4 - 7
Template for Class Definition
Import Statement
Class Comment
Describe the class in
the javadoc format.
class
{
Class Name
Declarations
Declare data members
shared by multiple
methods here.
. . .
Methods
}
5/25/2016
Introduction to Object-Oriented Programming with Java--Wu
Chapter 4 - 8
The CurrencyConverter Class
/**
* This class is used to do the currency conversion
* between a foreign currency and the U.S. dollar.
*
* @author Dr. Caffeine
*/
class CurrencyConverter
{
/**
* how much $1.00 U.S. is worth in the foreign currency
*/
private double exchangeRate;
//method declarations come here
}
5/25/2016
Introduction to Object-Oriented Programming with Java--Wu
Chapter 4 - 9
Method Declaration
<modifier>
<return type>
<method name>
( <parameters>
)
{
<statements>
}
Modifier
public
Return Type
void
Method Name
setExchangeRagte
Parameter
(
double
rate
{
exchangeRate = rate;
Statements
}
5/25/2016
Introduction to Object-Oriented Programming with Java--Wu
Chapter 4 - 10
)
Value-Returning Method
We call a method that returns a value a valuereturning method , or non-void method.
A value-returning method must include a return
statement in the following format:
return
<expression> ;
public double toDollar( double foreignMoney )
{
return (foreignMoney / exchangeRate);
}
5/25/2016
Introduction to Object-Oriented Programming with Java--Wu
Chapter 4 - 11
Method Header Comment in javadoc
/**
* Converts a given amount in dollars into
* an equivalent amount in a foreign currency.
*
* @param dollar the amount in dollars to be converted
*
* @return amount in foreign currency
*/
5/25/2016
Introduction to Object-Oriented Programming with Java--Wu
Chapter 4 - 12
Documenting a class
Let’s take a look at 151-152
You can model comments along these lines
Don’t forget our header though
5/25/2016
Introduction to Object-Oriented Programming with Java--Wu
Chapter 4 - 13
Constructors
A constructor is a special method that is executed
when a new instance of the class is created.
The purpose of the constructor is to initialize an
object to a valid state. Whenever an object is
created, we must ensure that it is created in a valid
state by properly initializing all data members in a
constructor.
The name of a constructor must be the same as the
name of the class.
If no constructor is defined for a class (e.g., the
original CurrencyConverter class), then the Java
compiler will include a default constructor.
5/25/2016
Introduction to Object-Oriented Programming with Java--Wu
Chapter 4 - 14
Default Constructor
The default constructor will have the following form:
public <class name> (
{
)
A default constructor has
no statements in its
method body.
}
public CurrencyConverter(
)
{
}
5/25/2016
Introduction to Object-Oriented Programming with Java--Wu
Chapter 4 - 15
Defining Constructors
A constructor will have the following form:
public <class name> ( <parameters
{
<statements>
)
}
Modifier
Class Name
Parameter
public CurrencyConverter( double rate
)
This constructor
ensures that the value
for exchangeRate is
set when a new
instance is created.
{
exchangeRate = rate;
Statements
}
5/25/2016
Introduction to Object-Oriented Programming with Java--Wu
Chapter 4 - 16
Multiple Constructors
A class can include multiple constructors without any
problem, as long as the constructors defined for the
class have either
A different number of parameters
Different data types for the parameters if the
number of parameters is the same
public MyClass( int
public MyClass(
value ) { … }
) { … }
public MyClass( float value ) { … }
5/25/2016
Introduction to Object-Oriented Programming with Java--Wu
These constructors will
not conflict with each
other, and therefore, valid.
Chapter 4 - 17
Visibility Modifiers: public and private
The modifiers public and private designate the
accessibility of data members and methods.
If a class component (data member or method) is
declared private, no outside methods can access it.
If a class component is declared public, any outside
method can access it.
class Test
{
public int memberOne;
private int memberTwo;
}
5/25/2016
Test myTest = new MyTest();
myTest.memberOne = 10;
myTest.memberTwo = 20;
Introduction to Object-Oriented Programming with Java--Wu
Chapter 4 - 18
Data Members Should Be private
Declare the data members (class and instance
variables) private to ensure the integrity of the class.
Data members are the implementation details of the
class, and they should be kept invisible from the
outside by declaring them private.
If a data member is declared public, then we cannot
make changes to the data member without affecting
all the classes that made direct access to this data
member.
Constants can (should) be declared public if they are
meant to be used directly by the outside methods.
5/25/2016
Introduction to Object-Oriented Programming with Java--Wu
Chapter 4 - 19
Local Variables
We covered instance and class variables that are
shared among the methods of the class.
A local variable is a variable that is declared within a
method declaration.
Local variables are accessible only from the method
in which they are declared.
Memory space for local variables are allocated only
during the execution of the method. When the
method execution completes, memory space will be
deallocated.
The parameters of a method are local to the method.
5/25/2016
Introduction to Object-Oriented Programming with Java--Wu
Chapter 4 - 20
Sample Method
public double fromDollar(
double
dollar
)
{
double
amount, fee;
Parameter
Local
Variables
fee
= exchangeRate - feeRate;
amount
= dollar * fee;
return amount;
}
5/25/2016
Introduction to Object-Oriented Programming with Java--Wu
Chapter 4 - 21
Memory Allocation for Local Variables - 1
Code
A
amt
= yenConverter.fromDollar( 200 );
public double fromDollar( double
dollar )
{
double amount, fee;
fee
= exchangeRate - feeRate;
amount = dollar * fee;
return amount;
}
At A before fromDollar
A. Local variables do
not exist before the
method execution
State of
Memory
5/25/2016
Introduction to Object-Oriented Programming with Java--Wu
Chapter 4 - 22
Memory Allocation for Local Variables - 2
Code
public double fromDollar( double
dollar )
{
double amount, fee;
fee
= exchangeRate - feeRate;
amount = dollar * fee;
return amount;
}
amt
= yenConverter.fromDollar( 200 );
After B
is executed
dollar
200.0
amount
State of
Memory
5/25/2016
B
B. Memory space is
allocated for the local
variables and parameter.
fee
Introduction to Object-Oriented Programming with Java--Wu
Chapter 4 - 23
Memory Allocation for Local Variables - 3
Code
public double fromDollar( double
dollar )
{
double amount, fee;
fee
= exchangeRate - feeRate;
amount = dollar * fee;
return amount;
}
amt
= yenConverter.fromDollar( 200 );
C
After C
is executed
dollar
State of
Memory
5/25/2016
200.0
amount
24846.3
fee
124.2315
Introduction to Object-Oriented Programming with Java--Wu
C. Computed values
are assigned to the local
variables.
Chapter 4 - 24
Memory Allocation for Local Variables - 4
Code
amt
= yenConverter.fromDollar( 200 );
D
public double fromDollar( double
dollar )
{
double amount, fee;
fee
= exchangeRate - feeRate;
amount = dollar * fee;
return amount;
}
At D after fromDollar
D. Memory space is
deallocated upon exiting
the fromDollar method.
State of
Memory
5/25/2016
Introduction to Object-Oriented Programming with Java--Wu
Chapter 4 - 25
Pass-By-Value Scheme - 1
Code
A
x = 10;
y = 20;
tester.myMethod( x, y );
public void myMethod( int one, float
two )
{
one = 25;
two = 35.4f;
}
At A before myMethod
x
State of
Memory
5/25/2016
y
10
A. Local variables do
20
10
Introduction to Object-Oriented Programming with Java--Wu
not exist before the
method execution
Chapter 4 - 26
Pass-By-Value Scheme - 2
Code
x = 10;
y = 20;
tester.myMethod( x, y );
public void myMethod( int one, float
two )
{
one = 25;
two = 35.4f;
}
Values are copied at
x
State of
Memory
5/25/2016
y
10
20
10
one
two
B
B
10
B. The values of
20.0f
10
Introduction to Object-Oriented Programming with Java--Wu
arguments are copied
to the parameters.
Chapter 4 - 27
Pass-By-Value Scheme - 3
Code
x = 10;
y = 20;
tester.myMethod( x, y );
public void myMethod( int one, float
two )
{
one = 25;
two = 35.4f;
}
C
After C
x
State of
Memory
5/25/2016
y
10
20
10
is executed
one
two
25
10
C. The values of
35.4f
10
Introduction to Object-Oriented Programming with Java--Wu
parameters are
changed.
Chapter 4 - 28
Pass-By-Value Scheme - 4
Code
x = 10;
y = 20;
tester.myMethod( x, y );
D
public void myMethod( int one, float
two )
{
one = 25;
two = 35.4f;
}
At D after myMethod
x
State of
Memory
5/25/2016
y
10
D. Parameters are
20
10
Introduction to Object-Oriented Programming with Java--Wu
erased. Arguments
remain unchanged.
Chapter 4 - 29
Arguments & Parameters: Points to Remember
1. Arguments are passed to a method using the pass-by-value
scheme.
2. Arguments are matched to the parameters from left to right.
The data type of an argument must be assignment compatible
to the data type of the matching parameter.
3. The number of arguments in the method call must match the
number of parameters in the method definition.
4. Parameters and arguments do not have to have the same
name.
5. Local copies, which are distinct from arguments, are created
even if the parameters and arguments share the same name.
6. Parameters are input to a method, and they are local to the
method. Changes made to the parameters will not affect the
value of corresponding arguments.
5/25/2016
Introduction to Object-Oriented Programming with Java--Wu
Chapter 4 - 30
Sample Program: Using an Instantiable Class
Problem Statement
Write a loan calculator program that computes both
monthly and total payments for a given loan amount,
annual interest rate, and loan period.
Major Tasks
1.
2.
3.
Get three input values
Compute the monthly and total payments
Output the results
Key Formula
L – loan amount
R – monthly interest rate
N – number of payments
5/25/2016
Introduction to Object-Oriented Programming with Java--Wu
Chapter 4 - 31
Program Design
5/25/2016
Introduction to Object-Oriented Programming with Java--Wu
Chapter 4 - 32
LoanCalculator Class
Design 1
Design 2
5/25/2016
Introduction to Object-Oriented Programming with Java--Wu
Chapter 4 - 33
Loan Calculator – Development Steps
1. Start with the main class and a skeleton of the
LoanCalculator class. The skeleton LoanCalculator class
will include only an object/variable declaration and a
constructor to create objects.
2. Implement the getInput method of LoanCalculator to
accept three input values.
3. Implement the displayOutput method of LoanCalculator
to display the results.
4. Implement the computePayment method of
LoanCalculator to compute the monthly and total
payments.
5. Implement the describeProgram method of
LoanCalculator to display a brief description of the
program.
5/25/2016
Introduction to Object-Oriented Programming with Java--Wu
Chapter 4 - 34