©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four...

61
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes

Transcript of ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four...

Page 1: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Chapter Four

Defining Your Own Classes

Page 2: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Chapter 4 Objectives

After you have read and studied this chapter, you should be able to

•Define an instantiable class with multiple methods and constructors.

•Differentiate the local and instance variables.

•Define and use value-returning methods.

•Distinguish private and public methods.

•Distinguish private and public data members.

Page 3: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Chapter 4 Objectives, cont.

After you have read and studied this chapter, you should be able to

•Describe how the arguments are passed to the parameters in method definitions.

•Describe how the result is returned from a method.

•Define a reusable class for handling input routines.

•Define an instantiable main class.

Page 4: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.1 Defining Instantiable Classes

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 DecimalFormat, GregorianCalendar, and String classes are all instantiable classes, while the Math class is not.

Page 5: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.1 Defining Instantiable Classes

Currency converter example: We need two methods for conversion: fromDollar and toDollar.

CurrencyConverter yenConverter;

double amountInYen, amountInDollar;

yenConverter = new CurrencyConverter( );

...

amountInYen = yenConverter.fromDollar(200); //from dollar to yen

amountInDollar = yenConverter.toDollar(15000);

//from yen to dollar

Page 6: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.1 Defining Instantiable Classes

Since the exchange rate fluctuates, we need a method to set the exchange rate.

CurrencyConverter yenConverter;

yenConverter = new CurrencyConverter( );

yenConverter.setExchangeRate(130.77);

Page 7: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.1 Defining Instantiable Classes

Class diagram for a CurrencyConverter object.

Page 8: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 4.1

A program template for a class definition.

Page 9: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.1 Defining Instantiable Classes

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);

amountInYen = yenConverter.fromDollar( 200 );

amountInMark = markConverter.fromDollar( 200 );

amountInDollar = yenConverter.toDollar( 10000 );

amountInMark = markConverter.fromDollar(amountInDollar);

Page 10: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 4.2

Every object of a class has its own copy of instance variables.

Page 11: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.1 Defining Instantiable Classes

Syntax for defining a method.

Page 12: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.1 Defining Instantiable Classes

If the method declaration includes the static modifier, it is a class method.

Class methods can access only class variables and constants.

Page 13: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.1 Defining Instantiable Classes

If the method declaration does not include the static modifier, it is an instance method.

Instance methods can access class variables and constants, as well as instance variables.

Page 14: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.1 Defining Instantiable Classes

We call a method that returns a value a value-returning 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);

}

Page 15: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.2 Instantiable Classes and 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 should ensure that it is created in a valid state by properly initializing all data members in a constructor.

Page 16: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.2 Instantiable Classes and Constructors

The name of a constructor must be the same as the name of the class.

If no constructor is defined for a class, then the Java compiler will include a default constructor.

Page 17: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.2 Instantiable Classes and Constructors

Syntax of a constructor.

Page 18: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.2 Instantiable Classes and Constructors

The default constructor will have the following form:

public <class name> ( ){

}

public CurrencyConverter( )

{

}

Page 19: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.2 Instantiable Classes and Constructors

A constructor does not have a return type.

It is possible to create multiple constructors for a class, as long as the constructors have either• A different number of parameters, or• Different data types for the

parameters if the number of parameters is the same.

Page 20: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.2 Instantiable Classes and Constructors

Examples of multiple constructors

public MyClass( int value ) { … }

public MyClass( ) { … }

public MyClass( float value ) { … }

Page 21: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.3 Information Hiding and Visibility Modifiers

Public methods of a class determine the behavior of its instances.

Internal details are implemented by private methods and private data members.

Declaring the data members private ensures the integrity of the class.

Page 22: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.3 Information Hiding and Visibility Modifiers

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.

Page 23: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.3 Information Hiding and Visibility Modifiers

Class constants may be declared public because:• A constant is “read only” by nature• A constant is a clean way to make

characteristics of the instances known to client programmers.

Public class data members are accessed by the syntax<class name>.<class data members>

Page 24: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.3 Information Hiding and Visibility Modifiers

Plus and minus signs designate public and private components, respectively.

Page 25: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.4 Local Variables, Return Values, and Parameter Passing

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.

Page 26: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.4 Local Variables, Return Values, and Parameter Passing

Memory space for local variables is allocated only during the execution of the method. When the method execution completes, memory space will be cleared.

The parameters of a method are local to the method.

Page 27: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.4 Local Variables, Return Values, and Parameter Passing

Sample method:

public double fromDollar( double dollar )

{

double amount, fee;

fee = exchangeRate - feeRate;

amount = dollar * fee;

return amount;

}

ParameterParameter

Local Variables

Local Variables

ParameterParameter

Local Variables

Local Variables

Page 28: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 4.3

Memory space for local variables and parameters is allocated and erased.

Page 29: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 4.3 cont.

Memory space for local variables and parameters is allocated and erased.

Page 30: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.4 Local Variables, Return Values, and Parameter Passing

When a method is called, the value of the argument is passed to the matching parameter, and separate memory space is allocated to store this value.

This way of passing the value of arguments is called a pass-by-value, or call-by-value, scheme.

Page 31: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.4 Local Variables, Return Values, and Parameter Passing

The data type of the argument must be assignment-compatible with the data type of the matching parameter.

Page 32: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 4.4

Memory space for the parameters is allocated and erased.

Page 33: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 4.4 cont.

Memory space for the parameters is allocated and erased.

Page 34: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.4 Local Variables, Return Values, and Parameter Passing

Parameters and return types are designated in the program diagram:

Page 35: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.4 Local Variables, Return Values, and Parameter Passing

The same designation applies to data members:

Page 36: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.5 Accessors, Mutators, and Overloaded Methods

A set method is called a mutator because it changes the property of an object.

An accessor is a method that returns a property of an object.

Page 37: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.5 Accessors, Mutators, and Overloaded Methods

Like constructors, methods may have the same name as long as the methods have either• A different number of parameters, or• Different data types for the

parameters if the number of parameters is the same.

The methods with the same name are called overloaded methods.

Page 38: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.5 Accessors, Mutators, and Overloaded Methods

Dot notation is optional when you call a method from another method if the two methods belong to the same object.

If dot notation is used, use the reserved word this to refer to the same object.

Page 39: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 4.5

Calling a method belonging to the same object vs. calling a method belonging to a different object.

Page 40: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.6 Passing and Returning Objects

Passing and returning objects follow the same process as passing and returning primitive data types.

The only difference is that with objects, the value being passed is the reference (or address) to an object.

Page 41: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.6 Passing and Returning Objects

When a variable is an object name, the value of the variable is the address in memory where the object is stored.

The effect of passing this value, or reference, is to have two variables (object names) referring to the same object.

Page 42: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 4.6

How an object is passed to a method.

Page 43: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 4.6 cont.

How an object is passed to a method.

Page 44: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 4.7

How an object is passed to a method (cont.).

Page 45: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 4.7 cont.

How an object is passed to a method (cont.).

Page 46: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 4.8

How an object is returned from a method.

Page 47: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 4.8 cont.

How an object is returned from a method.

Page 48: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 4.9

How an object is returned from a method.

Page 49: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 4.9 cont.

How an object is returned from a method.

Page 50: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.7 Modularizing the Input Routine Functionality

When a common task is repeated over and over, it is best to capture the common task into a class and use an instance of the class to perform the task.

Page 51: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.8 Organizing Classes into a Package

1. Include the statement package <package name>

as the first statement of the source file for the class you are packaging.

2.The class declaration must include the visibility modifier public.

3. Create a folder with the same name as the package name.

Page 52: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.8 Organizing Classes into a Package

4. Place the class into the folder and compile it.

5. Modify the CLASSPATH environment variable to include the folder that contains the package.

•Note that the steps to change the CLASSPATH environment variable are different for each platform and IDE.

Page 53: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.9 Sample Development: Defining and Using Instantiable Classes

Example: Loan and LoanCalculator classes.

1. Consider 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.

Page 54: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.9 Sample Development: Defining and Using Instantiable Classes

Develop overall plan:

1. Get three input values: loanAmount, interestRate, and loanPeriod.

2. Compute the monthly and total payments.

3. Output the results.

Page 55: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.9 Sample Development: Defining and Using Instantiable Classes

Five steps of implementation:

1. Start with the main class and a skeleton of the LoanCalculator class.•The skeleton class will include only

an object/variable declaration and a constructor to create objects.

•Define a temporary placeholder for the Loan class.

Page 56: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.9 Sample Development: Defining and Using Instantiable Classes

Five steps of implementation:

2. Implement the input routine to accept three input values.

3. Implement the output routine to display the results.

Page 57: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.9 Sample Development: Defining and Using Instantiable Classes

Five steps of implementation:

4. Implement the computation routine to compute the monthly and total payments.

5. Finalize the program, implementing any remaining temporary methods and adding necessary methods as appropriate.

Page 58: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 4.10

The program diagram for design alternative 1.

Page 59: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Fig. 4.11

The program diagram for alternative design 2.

Page 60: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

4.10 Making an Instantiable Class the Main Class

LoanCalculator example: Copy the main method of LoanCalculatorMain and paste it to the LoanCalculator class:

//Instantiable Main Class

class LoanCalculator {

//exactly the same code as before comes here

public static void main (String [ ] args) {

LoanCalculator loanCalculator;

loanCalculator = new LoanCalculator( );

loanCalculator.start( );

}

}

Page 61: ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

Javadoc comments

Javadoc comments begin with /** and end with */.

Javadoc tags are special markers that begin with @. For example:•@author•@param•@return