1 / 36

Windows Programming Using Java

Windows Programming Using Java. Instructor: Shih- Shinh Huang. Chapter6: Methods: A Deeper Look. Contents. Introduction Method Declaration and Usage static Method and Fields Declaration Scope Method Overloading Case Study. Introduction. Why Methods

yetta
Download Presentation

Windows Programming Using Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Windows Programming Using Java Instructor: Shih-Shinh Huang 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.

  4. boss worker1 worker2 worker3 worker4 worker5 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.

  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 • importstatements specify location of classes • importjava.util.Scanner; • public class GradeBook { • ……… • public voidDetermineAverage(){ • 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

  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 StringGetCourseName(){ • 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[]){ • GradeBookjavaGradeBook= 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 intMaximum(intx, float y, char z){ .. }/* End of Maximum */ intresult =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 • importjava.util.Scanner; • public classMaximumFinder { • 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 • importjava.util.Scanner; • public classMaximumFinder { • 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; • returnmaxValue; • }/* End of Maximum */ • }/* End of MaximumFinder */

  16. Method Declaration and Usage • public class MaximumFinderTest { • public static void main(String args[]){ • MaximumFindermaximumFinder = 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. private double Maximum( double x, double y, double z){...}; Invoke Maximum() Maximum(4, 100.0, 150); Maximum(4.0, 100.0, 150.0);

  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. public double Maximum (int x, int y, int z){......}; Invoke Maximum() Maximum(4, (int) 100.0, 150)

  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 staticvoid Main(string[] args){ }

  24. static Method and Fields • static Method • It can manipulate only class variables. public class Counter{ • privateintm_iCount; • privatestaticintm_iClassCount; • public staticvoid 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 Pop Push

  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.

  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 voidScopeExample(inta) { 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 (inti = 0; ...) {...} for (inti = 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 • 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

  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); void Maximum(int a, int b, int c); void Maximum(float a, float b);

  33. Method Overloading • public class MethodOverload { • public intSquare(intintValue){ • 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[]){ • MethodOverloadmethodOverload = new MethodOverload(); • intintResult = 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. • public class MethodOverload{ • public intSquare(intx){return x * x;} • public double Square(inty){return y * y;} • }/* End of MethodOverload */ Error: MethodOverload' already defines a member called 'Square' with the same parameter types

  36. Thank You ! www.themegallery.com

More Related