Download presentation
Presentation is loading. Please wait.
1
INSTRUCTOR: SHIH-SHINH HUANG Windows Programming Using Java Chapter6: Methods: A Deeper Look
2
Contents Introduction Method Declaration and Usage static Method and Fields Declaration Scope Method Overloading Case Study
3
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
4
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 worker1worker2worker3 worker4worker5
5
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 …………
6
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 */
7
Introduction Program Modules in Java PackageDescription java.appletJava applet-programs that execute in web browsers java.awtCreate and manipulate GUIs java.awt.eventEnable event handling in GUIs java.ioEnable programs to input and output data java.langIt is imported by the Java compiler java.netEnable program to communicate via network java.textEnable program to manipulate numbers, dates,… java.utilUtility classes java.swingProvide support for portable GUIs java.swing.eventEnable event handling for GUI components
8
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 }
9
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 */
10
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 */
11
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 */
12
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’);
13
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
14
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 */
15
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 */
16
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
17
Method Declaration and Usage Argument Promotion It implicitly converts an argument’s type to that the method expects to receive. 17 Maximum(4, 100.0, 150); private double Maximum( double x, double y, double z){...}; Maximum(4.0, 100.0, 150.0); Invoke Maximum()
18
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.
19
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()
20
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 “.”.
21
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 */
22
static Method and Fields Math.PI; // class variable Math.E; // class variable Math.x; // not accessible math1.x; // instance variable math2.x; // instance variable
23
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){ }
24
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 25 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. 26 The local variables can not be accessed anymore, if the corresponding activation record is popped off.
27
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.
28
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;...) {...} int c;// error: c is already declared in a nested block }/* End of Scope Example*/
29
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 */
30
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 */
31
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 */
32
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);
33
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 */
34
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
35
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
36
www.themegallery.com
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.