Download pptx

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Windows Programming
Using Java
Chapter6:
Methods: A Deeper Look
INSTRUCTOR: SHIH-SHINH HUANG
Contents
 Introduction
 Method Declaration and Usage
 static Method and Fields
 Declaration Scope
 Method Overloading
 Case Study
Introduction
 Why Methods
 Divide-and-Conquer:
develop a large application
from small and simple pieces.
 Reusability:
existing methods can be used as
building block to create new applications.
 Repeating
 Code
code can be avoided.
maintain will become easy.
3
Introduction
 Method Hierarchy
A
method is invoked by a method call
 The called method performs the task
 It returns the result or control to the caller.
boss
worker1
worker4
worker2
worker3
worker5
4
Introduction
 Program Modules in Java
 There
are three kinds of modules in Java: 1)
Methods, 2) Classes, and 3)Packages.
 Related
classes are grouped into packages.
 The
Java API provides a rich collection of
predefined classes
 Mathematical
 String
Calculation
Manipulation.
 Input/Output
 …………
Operations
Introduction
 Program Modules in Java
 import
statements specify location of classes
import java.util.Scanner;
public class GradeBook {
………
public void DetermineAverage(){
Scanner input = new Scanner(System.in);
while(count < 5){
…………
}/* End of while-loop */
………
}/* End of DetermineAverage */
}/* End of GradeBook */
Introduction
 Program Modules in Java
Package
Description
java.applet
Java applet-programs that execute in web browsers
java.awt
Create and manipulate GUIs
java.awt.event
Enable event handling in GUIs
java.io
Enable programs to input and output data
java.lang
It is imported by the Java compiler
java.net
Enable program to communicate via network
java.text
Enable program to manipulate numbers, dates,…
java.util
Utility classes
java.swing
Provide support for portable GUIs
java.swing.event
Enable event handling for GUI components
Method Declaration and Usage
 Method Declaration Format
return-value-type method-name( parameter-list )
{
declarations and statements
}
 Method-name:
any valid identifier
 Return-value-type: data type of the result
 void
- method returns nothing
 Return
at most one value
 Parameter-list:
comma separated list
Method Declaration and Usage
 Method Declaration Format
 Constructors
cannot return value even “void”
public class Triangle {
/* constructor */
public Triangle(int layer, char ch){
}/* End of constructor */
/* show the triangle pattern */
public void ShowTriangle(){
}/* ENd of ShowTriangle */
}/* End of Triangle */
Method Declaration and Usage
 Method Usage
 1)
Methods of the Class: method name and
arguments
public class GradeBook{
public String GetCourseName(){
return courseName;
} // end method getCourseName
public void DisplayMessage(){
System.out.printf( "Welcome to the grade book for
%s!\n", GetCourseName() );
}/* End of DisplayMessage */
}/* End of GradeBook */
Method Declaration and Usage
 Method Usage
 2)
Outside the Class: dot operator with
references to objects
public class GradeBook{
Void DisplayMessage(){
System.out.println(“Welcome to Java Course!”);
}/* End of DisplayMessage */
}/* End of class GradeBook */
public class GradeBookTest {
public static void main(String args[]){
GradeBook javaGradeBook = new GradeBook();
javaGradeBook.DisplayMessage();
}/* End of main */
}/* End of GradeBookTest */
Method Declaration and Usage
 Method Usage
 3)
Class Method: dot operator with references to
class name.
Math.sqrt(900.0);
Each argument must be consistent with the
type of the corresponding parameters.
public int Maximum(int x, float y, char z){
..
}/* End of Maximum */
int result = Maximum(1, 1.0, ‘a’);
Method Declaration and Usage
 Maximum Example
 Read
three values from user
 Find the maximum among them
 Print the maximum value
UML (Unified Modeling Language) Class Diagram
Method Declaration and Usage
import java.util.Scanner;
public class MaximumFinder {
public void DetermineMaximum(){
Scanner input = new Scanner(System.in);
System.out.print("Enter three floating-point separated by
spaces:");
double number1 = input.nextDouble();
double number2 = input.nextDouble();
double number3 = input.nextDouble();
double result = Maximum(number1, number2, number3);
System.out.printf("Maximum is: %f", result);
}/* End of DetremineMaximum */
private double Maximum(double x, double y, double z){……}
}/* End of MaximumFinder */
Method Declaration and Usage
import java.util.Scanner;
public class MaximumFinder {
public void DetermineMaximum(){
………
}/* End of DetremineMaximum */
private double Maximum(double x, double y, double z){
double maxValue = x;
if(y > maxValue) maxValue = y;
if(z > maxValue) maxValue = z;
return maxValue;
}/* End of Maximum */
}/* End of MaximumFinder */
Method Declaration and Usage
public class MaximumFinderTest {
public static void main(String args[]){
MaximumFinder maximumFinder = new MaximumFinder();
maximumFinder.DetermineMaximum();
}/* End of main */
}/* End of MaxiumumFinderTest */
Enter three floating-point separated by spaces:133.1 300 200
Maximum is: 300.000000
Method Declaration and Usage
 Argument Promotion
 It
implicitly converts an argument’s type to that
the method expects to receive.
private double Maximum(
double x, double y, double z){...};
Invoke Maximum()
Maximum(4, 100.0, 150);
Maximum(4.0, 100.0, 150.0);
17
Method Declaration and Usage
 Argument Promotion
 The
conversion may lead to compilation error if
Java’s promotion rule is violated.
 Promotion
Rule: the conversions should be
performed without losing data.
Method Declaration and Usage
 Casting
 You
can force the type conversion without
compiling error by using “cast” operator.
public double Maximum
(int x, int y, int z){......};
Invoke Maximum()
Maximum(4,
(int) 100.0,
150)
static Method and Fields
 static Fields
 Instance
Variable: Variables that every object
maintains its own copy in memory.

Class Variable: Only one copy of a particular
variable shared by all objects.
 The
keyword “static” is placed before the type to
declare as the class variable.
 It
can be accessed by the use of class name followed by
a dot “.”.
static Method and Fields
public class Math{
private static double PI=3.14159;
private static double E=2.718281;
private int x;
………
}/* End of Math */
public class MathTest {
public static void main(String args[]){
Math math1 = new Math();
Math math2 = new Math();
}/* End of main */
}/* End of MaxiumumFinderTest */
static Method and Fields
Math.PI;
// class variable
Math.E;
// class variable
Math.x;
// not accessible
math1.x; // instance variable
math2.x; // instance variable
static Method and Fields
 static Method
 Static
methods have behavior global to the class
and not specific to an instance.
 We
can declare a method as static by placing the
keyword “static” before return type.
public static void Main(string[] args){ }
 Invoke
Syntax: ClassName.methodName();
static Method and Fields
 static Method
 It
can manipulate only class variables.
public class Counter{
private int m_iCount;
private static int m_iClassCount;
public static void Increase(void){
m_iClassCount = 0;
m_iCount = 0;
}/* End of Counter */
}/* End of class Counter */
Declaration Scope
 Program Execution Stack
 Stack
is a last-in-first-out (LIFO) data structure.
 When
an application calls a method, the return
address is pushed onto the stack.
 This
stack is referred to program execution stack
/ method-call stack
Push
Pop
25
Declaration Scope
 Program Execution Stack
 When
the method is called, the memory of the
local variables is also allocated in the stack.
 This portion is called activation record.
 If stack for storing activation record is not
enough, an stack overflow error occurs.
The local variables can not be accessed
anymore, if the corresponding
activation record is popped off.
26
Declaration Scope
 Scope Rules
 The
scope of parameter declaration is the method
body where it appears.
 The
scope of local variable is from the declaration
point to the end of method.
 The
scope of local variable in the for header is
the body of for statement.
 The
scope of a method and fields of a class is the
body of the class.
Declaration Scope
public void ScopeExample(int a) {
int b;
if (...) {
int b;
// error: b is already declared in the outer block
int c;
...
} else {
int a;
// error: a is already declared in the outer block
}/* End of if-then-else */
for (int i = 0; ...) {...}
for (int i = 0; ...) {...}
int c;
// error: c is already declared in a nested block
}/* End of Scope Example*/
Declaration Scope
public class Scope {
private int x=1;
public void Example(){
int x=5;
………
}/* End of Example */
private void UseLocalVariable(){
int x=25;
System.out.printf(“x in method UseLocalVariable is %d\n",x);
x = x + 1;
System.out.printf(“x in method UseLocalVariable is %d\n",x);
}/* End of UseLocalVariable */
private void UseClassField(){
System.out.printf(“x in method UseClassField is %d\n",x);
x = x * 10;
System.out.printf(“x in method UseClassField is %d\n",x);
}/* End of UseClassField */
}/* End of Scope */
Declaration Scope
public class Scope {
private int x=1;
public void Example(){
int x=5;
System.out.printf("Local x in method Example is %d\n",x);
UseLocalVariable();
UseClassField();
UseLocalVariable();
UseClassField();
System.out.printf("Local x in method Example is %d\n",x);
}/* End of Example */
private void UseLocalVariable(){……}
private void UseClassField(){……}
}/* End of Scope */
Declaration Scope
public class ScopeTest {
public static void main(String args[]){
Scope scope = new Scope();
scope.Example();
}/* End of main */
}/* End of ScopeTest */
x in method Example is 5
x in method UseLocalVariable is 25
x in method UseLocalVariable is 26
x in method UseClassField is 1
x in method UseClassField is 10
x in method UseLocalVariable is 25
x in method UseLocalVariable is 26
x in method UseClassField is 10
x in method UseClassField is 100
x in method Example is 5
Method Overloading
 Overloading Description
 Methods of the same name can be declared in the
same class.
 It is commonly used to create several methods
that perform the same or similar tasks.
 Method signature is used to distinguish
overloaded methods.
 Parameter
Number
void Maximum(int a, int b);
 Parameter
Type
void Maximum(int a, int b, int c);
 Parameter
Order
void Maximum(float a, float b);
Method Overloading
public class MethodOverload {
public int Square(int intValue){
System.out.println("Method Square(int) ");
return intValue * intValue;
}/* End of Square */
public double Square(double doubleValue){
System.out.println("Method Square(float)");
return doubleValue * doubleValue;
}/* End of Square */
}/* MethodOverload */
Method Overloading
public class MethodOverloadTest {
public static void main(String args[]){
MethodOverload methodOverload = new MethodOverload();
int intResult = methodOverload.Square(7);
System.out.printf("Square: %d\n", intResult);
double doubleResult = methodOverload.Square(7.0);
System.out.printf("Square: %f\n", doubleResult);
}/* End of main */
}/* End of MethodOverloadTest */
Method Square(int)
Square: 49
Method Square(float)
Square: 49.000000
Method Overloading
 Remark
 Method
calls can not be distinguished only by
return value.
public class MethodOverload{
public int Square(int x){return x * x;}
public double Square(int y){return y * y;}
}/* End of MethodOverload */
Error: MethodOverload' already defines a member called 'Square'
with the same parameter types
35
www.themegallery.com
Related documents