1 / 43

An Introduction to Java Programming and Object-Oriented Application Development

An Introduction to Java Programming and Object-Oriented Application Development. Chapter 5 Methods and Classes. Objectives. In this chapter you will: Learn about the two types of methods in a Java program: predefined methods and programmer-defined methods

Télécharger la présentation

An Introduction to Java Programming and Object-Oriented Application Development

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. An Introduction to Java Programming and Object-Oriented Application Development Chapter 5 Methods and Classes

  2. Objectives In this chapter you will: • Learn about the two types of methods in a Java program: predefined methods and programmer-defined methods • Explore how to use a wide variety of predefined Java methods in the Math, String, NumberFormat, and GregorianCalendar classes • Learn how to create and apply programmer-defined methods within programs An Introduction to Java Programming and Object-Oriented Application Development

  3. Objectives (continued) • Explore the differences in static and instance class members • Learn how to pass variables to methods by value and by reference • Understand the scope of variables declared within a Java program An Introduction to Java Programming and Object-Oriented Application Development

  4. Methods and Classes • There are two basic kinds of methods in Java • Predefined methods • Programmer-defined methods • An argument is a literal variable or expression that is passed or sent when a method is called • If several arguments are included, they form an argument list • Example: JOptionPane.showInputDialog(menu) An Introduction to Java Programming and Object-Oriented Application Development

  5. Methods and Classes (continued) An Introduction to Java Programming and Object-Oriented Application Development

  6. Predefined Java Methods • Java contains predefined classes organized in packages • More than 160 packages and 3000 classes • The Java API http://java.sun.com/j2se/1.5.0/docs/api/ • Classes have two types of members • Method members • Data members An Introduction to Java Programming and Object-Oriented Application Development

  7. Working with Mathematical Functions • The class Math is in java.lang • The java.lang package does not need an import statement • To call a method in Math use this syntax: Math.<method name>() • The class name followed by the member access operator followed by parentheses • Parentheses may be empty or contain arguments • The member access operator is the dot operator An Introduction to Java Programming and Object-Oriented Application Development

  8. Working with Mathematical Functions (continued) • Example: pval = Math.pow(num1,num2); • JVM looks in the class Math of the method pow • The arguments are num1 and num2 • pow raises num1 to the power of num2 • The result is returned and stored in pval • Math has two fields • E, the natural logarithm base: 2.71828183 • PI, with value 3.14159265 • Access fields with the dot operator: Math.PI An Introduction to Java Programming and Object-Oriented Application Development

  9. Working with Mathematical Functions (continued) • A static method is a general method of a class • A static field is a general field of a class • Can be used without creating an object • An instance variable is owned by an individual object • An instance method can only be called by an object, not by a class An Introduction to Java Programming and Object-Oriented Application Development

  10. Working with Strings • The class String is in the package java.lang • The String class contains constructors • A constructor is a special method to create an object from a class • Math has no constructors; all methods are static • Most methods in String are instance methods An Introduction to Java Programming and Object-Oriented Application Development

  11. Working with Strings (continued) • Stringstr1=“Hello”; is a shortcut for Stringstr1=newString ({‘H’,‘e’,‘l’,‘l’,‘o’}); • Since str1 is an object of the String class, all methods in String can be called by it • Example: str1.substring(3); • Notice that the String object is calling the method (str1 calls substring) An Introduction to Java Programming and Object-Oriented Application Development

  12. Working with Strings (continued) • Static methods are called by the class: StringmyPi=String.valueOf(Math.PI); • Instance methods are called by an object of the class: String myL = “Hello”; int len = myL.length(); • The first character in a string has index 0 • myL.indexOf(‘e’) returns 1 An Introduction to Java Programming and Object-Oriented Application Development

  13. Formatting Numbers • The class NumberFormat has methods to format numbers for output • Complicated operations like rounding or converting a number to a percentage can be done using predefined methods • Using predefined methods makes code more accurate and reliable An Introduction to Java Programming and Object-Oriented Application Development

  14. Formatting Numbers (continued) • Create a NumberFormat object: NumberFormatmyNum=NumberFormat.getNumberInstance(); • Use the object to call additional (nonstatic) methods required for formatting: myNum.setMaximumFractionDigits(2); • Call the method format, with the literal or variable to be formatted: myNum.format(aDecimal); An Introduction to Java Programming and Object-Oriented Application Development

  15. Working with Times and Dates • The classes Calendar, GregorianCalendar and Date create time and date objects to use in processing • Calendar objects are created using the static method getInstance: Calendartoday=Calendar.getInstance(); • get accesses the MONTH, DAY, and YEAR fields in Calendar: int day = today.get(Calendar.MONTH); An Introduction to Java Programming and Object-Oriented Application Development

  16. Working with Times and Dates (continued) • Calendar is useful for processing information about specific dates and times • GregorianCalendar inherits all members of Calendar • public members of Calendar are accessible to GregorianCalendar • Create a GregorianCalendar object: GregorianCalendar today = new GregorianCalendar(); An Introduction to Java Programming and Object-Oriented Application Development

  17. Working with Times and Dates (continued) • The keyword new is the most common way of creating Java objects in memory • The class DateFormat formats date for output • DateFormat is in the package java.text • The output of Example 5.1 is 5 An Introduction to Java Programming and Object-Oriented Application Development

  18. Working with Times and Dates (continued) An Introduction to Java Programming and Object-Oriented Application Development

  19. Working with Times and Dates (continued) An Introduction to Java Programming and Object-Oriented Application Development

  20. Apply the Concept • Develop an application to calculate the value of an investment at retirement • Extract the date information from the input string • Use GregorianCalendar to convert date strings to date values for calculating interest • Interest is calculated using a financial formula • Output is formatted for display An Introduction to Java Programming and Object-Oriented Application Development

  21. Apply the Concept (continued) • Trim leading and trailing white space from the input name = name.trim(); • Extract information by looking for white space lastName = name.substring (i+1,name.length()); • Convert strings to integers month=Integer.parseInt(monthStr)–1; An Introduction to Java Programming and Object-Oriented Application Development

  22. Apply the Concept (continued) • The variable month is decremented because Java months start at 0 • GregorianCalendar objects convert dates to milliseconds and determine the number of years between to time values • Convert milliseconds to years with multiple divisions, ignoring leap years • Retirement amount is calculated by a standard formula An Introduction to Java Programming and Object-Oriented Application Development

  23. Apply the Concept (continued) • Retirement amount formatted as currency • Retirement date formatted as a long date • Date entered by user as 6/1/2018 displayed as “June 1, 2018” • Retirement amount displayed with $ and two decimal places An Introduction to Java Programming and Object-Oriented Application Development

  24. Programmer-Defined Methods • Previous section covered data members and method members of Java classes • Learned how to use predefined classes • Introduced inheritance (covered later) • Next: Programmer-defined methods An Introduction to Java Programming and Object-Oriented Application Development

  25. Overview of Programmer-Defined Methods • Methods make code more readable and allow the programmer to focus on smaller tasks • Complex projects can be delegated to many programmers • Code that will be executed multiple times can be modularized, making it less error-prone • Methods make code easier to maintain and reuse • Modularity is central to OO development An Introduction to Java Programming and Object-Oriented Application Development

  26. Anatomy of Programmer-Defined Methods and Method Calls • The code for predefined methods is not available to the programmer • Programmer-defined methods use a syntax like main • First line of code is the method heading • Access modifier: public • If the method is a class method: static • Return type: void (or String, int, Calendar…) • Method name: main • Parameter list: (String args[]) An Introduction to Java Programming and Object-Oriented Application Development

  27. Anatomy of Programmer-Defined Methods and Method Calls (continued) • The method name and parameter list are the method signature • The method body follows the method heading, enclosed in curly braces • The method body is a code block • If the method is never called, the method body never executes • Order of methods in the class does not matter An Introduction to Java Programming and Object-Oriented Application Development

  28. Passing Data to Methods: Primitive Variables and Reference Variables • Can pass data to methods using literals, such as findMax(2, 3) • Can pass data to methods using variables, as in findMax(x, y) • When variables are passed to methods, they are passed by value • Actual values of the variables are passed An Introduction to Java Programming and Object-Oriented Application Development

  29. Passing Data to Methods: Primitive Variables and Reference Variables (continued) • Variables in method headings are different memory locations than variables in method calls • A nonprimitive variable is a reference variable because it refers to an object • A primitive variable holds a value • When a method call passes a reference variable, the variable is passed by reference • The memory location of the variable is sent An Introduction to Java Programming and Object-Oriented Application Development

  30. The Scope of Variables • A Java file contains one or more classes and a class contains one or more methods • A method contains blocks of code enclosed in curly braces • A variable declared in the class outside of a method is available throughout the class • A variable declared in a code block or parameter list has scope only within the block or method • When program flow leaves a block, variables with local scope are destroyed An Introduction to Java Programming and Object-Oriented Application Development

  31. Apply the Concept • Modify code from Chapter 4 (Figure 4.24) to incorporate programmer-defined methods • The only difference is that some of the processing logic is located in separate methods • The method calculateAndDisplayAvg is called with arguments totalIncome, numberOfEntries, and currencyFormatter • The parameters in the method heading have slightly different names to avoid confusion An Introduction to Java Programming and Object-Oriented Application Development

  32. Apply the Concept (continued) An Introduction to Java Programming and Object-Oriented Application Development

  33. Apply the Concept (continued) An Introduction to Java Programming and Object-Oriented Application Development

  34. Apply the Concept (continued) • Using currencyFormatter in calculateAndDisplayAvg without passing it, as an argument generates a compiler error An Introduction to Java Programming and Object-Oriented Application Development

  35. Apply the Concept (continued) An Introduction to Java Programming and Object-Oriented Application Development

  36. Case Study: MusicWorld • MusicWorldApp4 allowed a user to enter data for multiple-item CD order • Displayed total with quantity discount and tax • MusicWorldApp5.java will modularize the program • Currency and Percent formatting will improve the display An Introduction to Java Programming and Object-Oriented Application Development

  37. The Flowchart of MusicWorldApp5 • The flowchart is virtually identical to MusicWorldApp4 • Two methods accomplish the same functionality but make the code more readable An Introduction to Java Programming and Object-Oriented Application Development

  38. The Flowchart of MusicWorldApp5 (continued) An Introduction to Java Programming and Object-Oriented Application Development

  39. Program Code for MusicWorldApp5 • Create a DecimalFormat object by casting NumberFormat • DecimalFormat dF = (DecimalFormat NumberFormat.getPercentInstance(); • The method applyPattern in the class DecimalFormat • # represents integers, 0 represents decimal places and % represents percentage • dF.applyPattern(“###.000%”); An Introduction to Java Programming and Object-Oriented Application Development

  40. Program Code for MusicWorldApp5 (continued) • Method calls to displayItemOutput • Different variable names in the method call and the method header make the code more readable • Return statement sends back a reference to a String to main • Method displayItemOutput calculates the order total • Output is virtually the same, but the currency is formatted in a more acceptable way An Introduction to Java Programming and Object-Oriented Application Development

  41. Summary • Two kinds of methods in Java • Predefined methods in the Java API • Programmer-defined methods • Methods are executed when they are called • An argument is passed to a method when it is called • Static members are accessed by the class • Instance members are accessed by objects in the class An Introduction to Java Programming and Object-Oriented Application Development

  42. Summary (continued) • NumberFormat is in java.text and has methods to format currency, percentages, and decimals • Calendar and GregorianCalendar are in java.util and have methods to format times and dates • A method definition consists of a method heading followed by program code within {} • The parameter list in a method call must agree in number and data type and order with the method definition An Introduction to Java Programming and Object-Oriented Application Development

  43. Summary (continued) • Primitive variables represent primitive data types and are passed by value • Reference variables represent objects and are passed by reference • A variable that is defined in a method or block only has scope within that block • Variables declared within a class, outside of a method, are accessible everywhere in the class An Introduction to Java Programming and Object-Oriented Application Development

More Related