0% found this document useful (0 votes)
15 views

jhtp10_ch05_methods

oop

Uploaded by

zohrajabeen1011
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

jhtp10_ch05_methods

oop

Uploaded by

zohrajabeen1011
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 84

Java How to Program,

Late Objects Version, 10/e

© 1992-2015 by Pearson Education, Inc. All Rights


Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 Best way to develop and maintain a large program is to
construct it from small, simple pieces.
◦ called divide and conquer
 Methods facilitate the design, implementation,
operation and maintenance of large programs.
 Normally, methods are called on specific objects
 static methods can be called on a class rather than

an object.

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 You write Java programs by combining new methods
and classes that you write with predefined available in
the Java Application Programming Interface and in
various other class libraries
 Related classes are typically grouped into packages so

that they can be imported into programs and reused


 The Java API provides a rich collection of predefined

classes

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 The statements in method bodies are written only once,
are hidden from other methods and can be reused from
several locations in a program.
 Software reusability

◦ using existing methods as building blocks to create new


programs
 Often, you can create programs from existing classes
and methods rather than by building customized code
 Dividing a program into meaningful methods makes

the program easier to debug and maintain.

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 A method is invoked by a method call
 When the called method completes its task, it returns
control—and possibly a result—to the caller
 Similar to the hierarchical form of management (Fig. 5.1)
◦ A boss (the caller) asks a worker (the called method) to perform a
task and report back (return) the results after completing the task
◦ The boss method does not know how the worker method performs its
designated tasks
◦ The worker may also call other worker methods, unbeknown to the
boss
◦ This “hiding” of implementation details promotes good software
engineering

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 Sometimes a method performs a task that does not depend
on the contents of any object
◦ Method applies to the class in which it’s declared as a whole and is
known as a static method or a class method
 For any class imported into your program, you can call the
class’s static methods by specifying the name of the
class in which the method is declared, followed by a dot (.)
and the method name
 All Math class methods are static
◦ Each is called by preceding the name of the method with the class
name Math and the dot (.) separator
 Method arguments may be constants, variables or
expressions

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 Class Math declares two constants
◦ Math.PI (3.141592653589793) is the ratio of a circle’s
circumference to its diameter
◦ Math.E (2.718281828459045) is the base value for natural
logarithms (calculated with static Math method log)
 These constants are declared in class Math with the
modifiers public, static and final.
◦ public allows you to use these fields in your own classes
◦ static allows them to be accessed via the class name Math and a
dot (.) separator
◦ final indicates that they are constants—value cannot change after
they are initialized.
 A class’s variables are sometimes called fields.

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
Why Is Method main Declared static?
When you execute the Java Virtual Machine (JVM)

with the java command, the JVM attempts to invoke


the main method of the class you specify
Declaring main as static allows the JVM to invoke

main without creating an object of the class

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 Class MaximumFinder (Fig. 5.3) has two methods—
main (lines 8–25) and maximum (lines 28–41)
 The maximum method determines and returns the

largest of three double values


 Most methods do not get called automatically

◦ You must call method maximum explicitly to tell it to perform


its task

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 A public method is “available to the public”
◦ Can be called from methods of other classes
 static methods in the same class can call each other
directly
◦ Any other class that uses a static method must fully qualify
the method name with the class name
 For now, we begin every method declaration with the
keywords public and static
◦ You’ll learn about non-public and non-static methods in
Chapter 7.

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 Return type
◦ Specifies the type of data a method returns (that is, gives back
to its caller) to the calling method after performing its task
 In some cases, you’ll define methods that perform a
task but will not return any information
◦ Such methods use the return type void.

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 The method name follows the return type
 Class names, method names and variable names are all identifiers
and by convention all use the same camel case naming scheme
we discussed in Chapter 2.
 Class names begin with an initial uppercase letter, and method
names and variable names begin with an initial lowercase letter.
 For a method that requires additional information to perform its
task, the method can specify one or more parameters that
represent that additional information.
◦ Defined in a comma-separated parameter-list located in the parentheses
that follow the method name
◦ Each parameter must specify a type and an identifier
 A method’s parameters are considered to be local variables of
that method and can be used only in that method’s body

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 Method header
◦ Modifiers, return type, method name and parameters
 Method body
◦ Delimited by left and right braces
◦ Contains one or more statements that perform the method’s task
 A return statement returns a value (or just control) to the
point in the program from which the method was called

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 String concatenation allows you to assemble String objects
into larger strings by using operators + or +=
 When both operands of operator + are String objects, operator
+ creates a new String object in which the characters of the
right operand are placed at the end of those in the left operand
 Every primitive value and object in Java can be represented as a
String
 When one of the + operator’s operands is a String, the other is
converted to a String, then the two are concatenated
◦ If a boolean is concatenated with a String, the boolean is
converted to the String "true" or "false"
◦ When an object is concatenated with a String, the object’s
toString method is implicitly called to obtain the String
representation of the object

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
Implementing Method maximum by Reusing Method Math.max
The entire body of our maximum method could also be
implemented with two calls to Math.max, as follows:
 return Math.max(x, Math.max(y, z));
Theouter call to Math.max specifies arguments x and
Math.max(y, z).

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 Three ways to call a method:
◦ Using a method name by itself to call another method of the
same class
◦ Using an object’s variable name followed by a dot (.) and the
method name to call a non-static method of the object
◦ Using the class name and a dot (.) to call a static method
of a class

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 There are three ways to return control to the statement
that calls a method
 If the method does not return a result, control returns

when the program flow reaches the method-ending


right brace or when the statement return; executes
 If the method returns a result, the statement
 return expression;
evaluates the expression, then returns the result to the
caller

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 Stack data structure
◦ Analogous to a pile of dishes
◦ When a dish is placed on the pile, it’s normally placed at the
top (referred to as pushing onto the stack)
◦ Similarly, when a dish is removed from the pile, it’s normally
removed from the top (referred to as popping off the stack)
 Last-in, first-out (LIFO) data structures—the last item
pushed onto the stack is the first item popped from the
stack

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 When a program calls a method, the called method must
know how to return to its caller, so the return address of the
calling method is pushed onto the method-call stack
 If a series of method calls occurs, the successive return
addresses are pushed onto the stack in last-in, first-out order
 The method-call stack also contains the memory for the
local variables (including the method parameters) used in
each invocation of a method
◦ This data, stored as a portion of the method-call stack, is known as
the stack frame (or activation record) of the method call
◦ When a method call is made, the stack frame for that method call is
pushed onto the method call stack
 When a method returns to its caller, the stack frame for the
method call is popped off the stack and those local variables
are no longer known to the program

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 Argument promotion—converting an argument’s value, if
possible, to the type that the method expects to receive in its
corresponding parameter
 Such conversions may lead to compilation errors if Java’s
promotion rules are not satisfied
 These rules specify which conversions are allowed—that is,
which ones can be performed without losing data
 The promotion rules apply to expressions containing values of
two or more primitive types and to primitive-type values passed
as arguments to methods
 Each value is promoted to the “highest” type in the expression
 Figure 5.4 lists the primitive types and the types to which each
can be promoted

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 Java contains many predefined classes that are grouped into categories
of related classes called packages
 Known as the Java Application Programming Interface (Java API), or
the Java class library
 Some key Java API packages are described in Fig. 5.5
 Overview of the packages in Java
 http://docs.oracle.com/javase/7/docs/api/overview-summary.
html
 http://download.java.net/jdk8/docs/api/overview-summary.ht
ml
 Additional information about a predefined Java class’s methods
 http://docs.oracle.com/javase/7/docs/api/
◦ Index link shows alphabetical list of all the classes and methods in the Java API
◦ Locate the class name and click its link to see the online description of the class
◦ METHOD link shows a table of the class’s methods
◦ Each static method will be listed with the word “static” preceding its
return type

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 The element of chance can be introduced in a program via
an object of class SecureRandom (package
java.security).
 Such objects can produce random boolean, byte,
float, double, int, long and Gaussian values.
 SecureRandom objects produce nondeterministic random
numbers that cannot be predicted.
 Deterministic random numbers have been the source of
many software security breaches.

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 If truly random, then every value in the range should have
an equal chance (or probability) of being chosen each time
nextInt is called
 Class Random provides another version of method
nextInt that receives an int argument and returns a
value from 0 up to, but not including, the argument’s value

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 scaling factor—represents the number of unique values
that nextInt should produce
 shift the range of numbers produced by adding a

shifting value

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 Generalized scaling and shifting of random numbers:
 number = shiftingValue +
randomNumbers.nextInt(scalingFactor);
where shiftingValue specifies the first number in the desired
range of consecutive integers and scalingFactor specifies how
many numbers are in the range
 Choose integers at random from sets of values other than ranges
of consecutive integers, generalized as
 number = shiftingValue + differenceBetweenValues *
randomNumbers.nextInt(scalingFactor);
where shiftingValue specifies the first number in the desired
range of values, differenceBetweenValues represents the constant
difference between consecutive numbers in the sequence and
scalingFactor specifies how many numbers are in the range

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 Rules for the dice game Craps:
◦ You roll two dice. Each die has six faces, which contain one,
two, three, four, five and six spots, respectively. After the dice
have come to rest, the sum of the spots on the two upward
faces is calculated. If the sum is 7 or 11 on the first throw, you
win. If the sum is 2, 3 or 12 on the first throw (called “craps”),
you lose (i.e., the “house” wins). If the sum is 4, 5, 6, 8, 9 or 10
on the first throw, that sum becomes your “point.” To win, you
must continue rolling the dice until you “make your point”
(i.e., roll that same point value). You lose by rolling a 7 before
making your point.
 The application in Fig. 5.8 simulates the game of craps,
using methods to implement the game’s logic

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 Type Status is a private member of class Craps,
because Status will be used only in that class
 Status is an enum type
◦ Declares a set of constants represented by identifiers
◦ Special kind of class that is introduced by the keyword enum and a
type name
 Braces delimit an enum declaration’s body
 Inside the braces is a comma-separated list of enum
constants, each representing a unique value
 The identifiers in an enum must be unique
 Variables of an enum type can be assigned only the
constants declared in the enum

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 Why we declare some constants as public final
static int rather than as enum constants:
◦ Java does not allow an int to be compared to an enum
constant
 Unfortunately, Java does not provide an easy way to
convert an int value to a particular enum constant

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 Declarations introduce names that can be used to refer
to classes, methods, variables and parameters
 The scope of a declaration is the portion of the program

that can refer to the declared entity by its name


 Such an entity is said to be “in scope” for that portion

of the program

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 Basic scope rules:
◦ The scope of a parameter declaration is the body of the method
in which the declaration appears.
◦ The scope of a local-variable declaration is from the point at
which the declaration appears to the end of that block.
◦ The scope of a local-variable declaration that appears in the
initialization section of a for statement’s header is the body
of the for statement and the other expressions in the header.
◦ A method or field’s scope is the entire body of the class.

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 Any block may contain variable declarations
 If a local variable or parameter in a method has the

same name as a field of the class, the field is hidden


until the block terminates execution
◦ Called shadowing
 Figure 5.9 demonstrates scoping issues with static
and local variables.

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 Methods of the same name can be declared in the same
class, as long as they have different sets of parameters
◦ Called method overloading
◦ The compiler selects the appropriate method to call by examining the
number, types and order of the arguments in the call
 Used to create several methods that perform the same or
similar tasks on different types or different numbers of
arguments
 Math methods abs, min and max are overloaded with
four versions each:
◦ One with two double parameters
◦ One with two float parameters
◦ One with two int parameters
◦ One with two long parameters

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 Literal integer values are treated as type int
 Literal floating-point values are treated as type

double
 By default, floating-point values are displayed with six

digits of precision if the precision is not specified in the


format specifier.

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 Compiler distinguishes overloaded methods by their
signatures
◦ A combination of the method’s name and the number, types and
order of its parameters, but not its return type.
 Internally, the compiler uses longer method names that
include the original method name, the types of each
parameter and the exact order of the parameters to
determine whether the methods in a class are unique in that
class.
 Method calls cannot be distinguished by return type
◦ Overloaded methods can have different return types if the methods
have different parameter lists
 Overloaded methods need not have the same number of
parameters

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
 Colors displayed on computer screens are defined by their red,
green, and blue components (called RGB values
◦ Integer values from 0 to 255
◦ The higher the value of a component color, the richer that color’s shade
will be
 Class Color (package java.awt) represents colors using their
RGB values
 Class Color contains various predefined static Color
objects
◦ BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN, LIGHT_GRAY,
MAGENTA, ORANGE, PINK, RED, WHITE and YELLOW
◦ Each can be accessed via the class name and a dot (.) as in
Color.RED
 You can create custom color by passing the red-, green- and
blue-component values to class Color’s constructor.

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
 Graphics methods fillRect and fillOval
draw filled rectangles and ovals, respectively
 These have the same parameters as drawRect and

drawOval; the first two are the coordinates for the


upper-left corner of the shape, while the next two
determine the width and height
 Graphics method setColor seta the current

drawing color

© 1992-2015 by Pearson Education, Inc.


All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.
© 1992-2015 by Pearson Education, Inc.
All Rights Reserved.

You might also like