instructor: shih-shinh huang windows programming using java chapter6: methods: a deeper look

36
INSTRUCTOR: SHIH-SHINH HUANG Windows Programming Using Java Chapter6: Methods: A Deeper Look

Post on 22-Dec-2015

222 views

Category:

Documents


0 download

TRANSCRIPT

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 can be avoided. Code 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.

4

boss

worker1 worker2 worker3

worker4 worker5

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 Calculation String Manipulation. Input/Output Operations …………

Introduction

Program Modules in Java import statements specify location of

classesimport 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 JavaPackage 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

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

return-value-type method-name( parameter-list ){ declarations and statements}

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 objectspublic 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 200Maximum is: 300.000000

17

Method Declaration and Usage

Argument Promotion It implicitly converts an argument’s type

to that the method expects to receive.

Maximum(4, 100.0, 150);

private double Maximum(double x, double y, double z)

{...};

Maximum(4.0, 100.0, 150.0);

Invoke Maximum()

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.

Maximum(4, (int) 100.0, 150)

public double Maximum(int x, int y, int z){......};

Invoke Maximum()

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

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.

Invoke Syntax: ClassName.methodName();

public static void Main(string[] args){ }

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 */

25

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

26

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.

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

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

public class ScopeTest {

public static void main(String args[]){

Scope scope = new Scope();

scope.Example();

}/* End of main */

}/* End of ScopeTest */

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 Parameter Type Parameter Order

void Maximum(int a, int b, int c);

void Maximum(float a, float b);

void Maximum(int a, int 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: 49Method Square(float)Square: 49.000000

Method Overloading

Remark Method calls can not be distinguished only

by return value.

35

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

www.themegallery.com