Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
2/20/2014
1
Manipulation of objects
(Methods in Java)
Chapters 6 and 8
Sharma Chakravarthy
Information Technology Laboratory (IT Lab)
Computer Science and Engineering Department
The University of Texas at Arlington, Arlington, TX 76019
Email: sharma@cse.uta.edu
Course URL: wweb.uta.edu/faculty/sharmac
URL: http://itlab.uta.edu/sharma
Program Modules in Java 
• Java programs combine new methods and classes that 
you write with predefined methods and classes 
available in the Java Application Programming 
Interface (JAVA API) and in other class libraries. 
• Related classes are typically grouped into packages so 
that they can be imported into programs and reused. 
– You’ll learn how to group your own classes into 
packages in Chapter 8. 
6.2 Program Modules in Java (Cont.)
• Methods help you modularize a program by separating its 
tasks into self-contained units. 
• Statements in method bodies
– Written only once
– Hidden from other methods
– Can be reused from several locations in a program
• Divide-and-conquer approach
– Constructing programs from small, simple pieces
• Software reusability
– Use existing methods as building blocks to create new programs. 
• Dividing a program into meaningful methods makes the 
program easier to debug and maintain.
2/20/2014
2
Program Modules in Java (Cont.)
• Hierarchical form of management (Fig. 6.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. 
• “Hiding” of implementation details promotes good 
software engineering. 
• Data hiding vs. computation hiding or delegation
• The method toString() is a good example of 
delegation. Can be called on any object without 
having to worry about its structure.
• But you have to write it for your classes!
• True for constructors and methods you write
 Sometimes a method performs a task that does not depend on the 
contents of any object. 
 Applies to the class in which it is declared as a whole 
 Known as a static method or a class method
 It’s common for classes to contain convenient static methods 
to perform common tasks. 
 To declare a method as static, place the keyword static
before the return type in the method’s declaration. 
 Calling a static method 
 ClassName.methodName( arguments ) //not an object
 Class Math provides a collection of static methods that 
enable you to perform common mathematical calculations. 
 Method arguments may be constants, variables or expressions. 
2/20/2014
3
• We also saw a bunch of static methods in the Arrays class.
• Perhaps, static methods come closest to C functions
all parameters are (have to be) passed explicitly
no implicit parameter (this) as in an instance method invocation
• Most of the methods you will be writing will be instance (or non-
static) methods
• Design should include this differentiation as needed
 Math fields for common mathematical constants
 Math.PI (3.141592653589793)
 Math.E (2.718281828459045)
 Declared in class Math with the modifiers public, 
final and static
 public allows you to use these fields in your own classes 
directly
 A field declared with keyword final is constant—its value 
cannot change after the field is initialized. 
 PI and E are declared final because their values never 
change. 
2/20/2014
4
 A field that represents an attribute is also known as an 
instance variable -- each object (instance) of the class 
has a separate instance of the variable in memory. 
 Fields for which each object of a class does not have a 
separate instance of the field are declared static and 
are also known as class variables. 
 All objects of a class containing static fields share 
one copy of those fields. 
 Together the class variables (i.e., static variables) 
and instance variables represent the fields of a class. 
Classes and Methods
1. Class Fields/attributes
– class and instance attributes
2. Class members
– Class fields/attributes
– Methods (including constructors)
3. Method format
Accessibility mod class/instance mod type mod method name parameter (not argument)
public static void methodName(parameters){…}
private  
protected

 corresponds to package‐private!
 Multiple parameters are specified as a comma-
separated list. 
 There must be one argument in the method call for each 
parameter (sometimes called a formal parameter) is in 
the method declaration. 
 Each argument must be consistent with the type of the 
corresponding parameter. 
 An argument can be a constant, variable (including 
reference type), or an expression (makes it very 
powerful, can be nested, invoke constructors/methods)
2/20/2014
5
If you want to return multiple values, encapsulate them in 
an object and return the object (actually object reference!)
2/20/2014
6
Remember,
float x, y;
float number1 = 20.3, number2;
Is fine for the declaration of variables, but not as parameters
Each parameter should have its type preceding it
 Implementing method maximum by reusing method 
Math.max
 Two calls to Math.max, as follows:
 return Math.max( x, Math.max( y, z ) );
 The first specifies arguments x and Math.max( y, z ). 
 Before any method can be called, its arguments must be 
evaluated to determine their values. 
 If an argument is a method call, the method call must be 
performed to determine its return value. 
 The result of the first call is passed as the second argument to 
the other call, which returns the larger of its two arguments. 
 String concatenation 
 Assemble String objects into larger strings with operators + or +=. 
 When both operands of operator + are Strings, operator +
creates a new String object 
 characters of the right operand are placed at the end of those in the left 
operand
 Every primitive value and object in Java has a String
representation. 
 When one of the + operator’s operands is a String, the other is 
converted to a String, then the two are concatenated.  
String empId =  “emp” + 1 will result in  ____ 
 If a boolean is concatenated with a String, the boolean is 
converted to the String "true" or "false". 
2/20/2014
7
(C) 2010 Pearson Education, Inc.  All 
rights reserved.
 Variable-length argument lists
 Can be used to create methods that receive an unspecified 
number of arguments. 
 Parameter type followed by an ellipsis (...) indicates that the 
method receives a variable number of arguments of that 
particular type. 
 The ellipsis can occur only once at the end of a parameter list.
 That should be the  last argument (there can be other 
arguments)
 And must be of the same type (obviously)
(C) 2010 Pearson Education, Inc.  All 
rights reserved.
(C) 2010 Pearson Education, Inc.  All 
rights reserved.
2/20/2014
8
 Three ways to call a method: 
 Using only the  method name by itself to call another method 
(both instance and class) of the same class
 e.g., isValid(m, d, y)
 Using a variable that contains a reference to an object, 
followed by a dot (.) and the method name to call a method of 
the referenced object
 E.g., startDate.next()
 Using the class name and a dot (.) to call a static method 
of a class
 Math.random(), Time.intervalOverlap(t1From, t1To, t2From, t2To)
 A non-static method can call any method of the 
same class directly and can manipulate any of the 
class’s fields directly. 
 A static method can call only other static
methods of the same class directly and can manipulate 
only static fields in the same class directly. 
 To access the class’s non-static members, a static
method must use a reference to an object of the class. 
 Understand the above clearly!
 Three ways to return control to the statement that calls 
a method: 
 When the program flow reaches the method-ending right brace
 This is good ONLY for void methods 
 When the following statement executes
return;
can be used in void methods as well!
 When the method returns a result with a statement like
return expression;
has to have an expression for value-
returning methods!
Java methods cannot be nested!
We will later learn more about Java 
nested classes
2/20/2014
9
Distinguish this from a shadow variable where the 
name is the same as some filed/attribute  of the class !
However, a parameter can be re-declared in an inner 
scope of a method (e.g., for loop, while loop, etc.) 
Example:   
public int sum(int i1, int i2){
int i2 //not allowed; compiler gives error! WHY?
for (int i1=0; i1 < i2; i1++) System.out.println(i1, i2);
return i1+i2 // allowed, gives no error
} //note that the parameter i1  will not be available 
//inside the for loop 
// bad practice!
Scoping
• Static (also known as lexical) scoping follows 
the property of the program text and is 
unrelated to the runtime call stack
– Static scoping is determined at compile time
• Used by most programming languages
• A variable always refers to its nearest 
enclosing binding – closest nested scope rule
• Look for a declaration in the current innermost scope
• If there is none, look for a declaration in the 
immediately surrounding (lexical) scope, etc.
Static Scoping
• Matching a variable to its binding only requires 
analysis of the program text
• Static scope binding can be understood in isolation 
from the program (and does not have to take all 
possible invocations into account)
• Scoping need to resolve multiple declarations of the 
same name and variables used in nested blocks
• In java, method or field name can be used before the 
definition/declaration appears (remember, fields can 
be listed at the bottom of the class)
– Not true for a local variable!
Scoping
• Understand the differences between static (or lexical) scoping and dynamic 
(or run time) scoping
• the difference between a heap and a stack
• Need for both stack and heap at run time
Public static void main(String[] args){
int L = 20;
char K; 
double R; 
for (int j=0; j