Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Chapter 4 How to write object-oriented programs CS170 ygao JAVA, C4 Slide 1 Objectives Describe the concept of encapsulation and explain its importance to object-oriented programming. Describe a signature of a constructor or method, and explain what overloading means. Code the instance variables, constructors, and methods of a class that defines an object. Code a class that creates objects from a user-defined class and then uses the methods of the objects to accomplish the required tasks. Code a class that contains static fields and methods, and call these fields and methods from other classes. Add two or more classes to a package and make the classes in that package available to other classes. Code javadoc comments for a class, and generate the documentation for the class. Then, use your web browser to review that documentation. CS170 ygao JAVA, C4 Slide 2 Concept of Encapsulation • What is encapsulation? - data and functions/methods are packaged together in the class normally with the same scope of the accessibility in the memory • Why encapsulation - Objects no longer need to be dependent upon any “outside” functions and data after the creation - Provide ADT (Abstract Data Types) - Easier in coding - Promote standards in OOP CS170 ygao JAVA, C4 Slide 3 Classes vs. Objects • Class is a data structure that encapsulates data and functions. • Data in a class are called member data, class variables, instance variables, or fields. • Functions in a class are called member functions or methods. Constructors are special methods. • Objects are the instance of a class. Creation of the objects and instantiation of the objects are all referring to memory allocation to hold the data and methods of the objects. In Java, all objects are created dynamically using new operator. For example: ClassName ObjName = new ClassName(); CS170 ygao JAVA, C4 Slide 4 A class diagram for the Book class Book -code: String -title: String -price : double +setTitle(code: String) +setPrice(code: String) +getCode(): String +getTitle(): String +getPrice(): double CS170 ygao JAVA, C4 class name attributes /member data operations / methods Slide 5 The relationship between a class and its objects Book -code: String -title: String -price: double book1 -code = "WARP" -title = "War and Peace" -price = 14.95 book2 -code = "MBDK" -title = "Moby Dick" -price = 12.95 Note: Diagrams do not include methods, just for demo CS170 ygao JAVA, C4 Slide 6 The Book class public class Book{ private String code; private String title; private double price; Instance variables/member data public Book(String bookCode){ code = bookCode; setTitle(bookCode); setPrice(bookCode); } Constructor public void setTitle(String bookCode){ if (bookCode.equalsIgnoreCase("WARP")) title = "War and Peace"; else if (bookCode.equalsIgnoreCase("MBDK")) title = "Moby Dick"; else title = "Not Found"; } CS170 ygao JAVA, C4 Method Slide 7 The Book class (continued) public void setPrice(String bookCode){ if (bookCode.equalsIgnoreCase("WARP")) price = 14.95; else if (bookCode.equalsIgnoreCase("MBDK")) price = 12.95; else price = 0.0; } public String getCode(){ return code; } More methods public String getTitle(){ return title; } public double getPrice(){ return price; } } CS170 ygao JAVA, C4 Slide 8 The syntax for declaring instance variables public|private|protected primitiveType|ClassName variableName; Examples private double price; private int quantity; private String title; private Book bookObject; CS170 ygao JAVA, C4 Slide 9 Characteristics of Constructors • A special method that has the same name of the class without return type, not even void. • Constructor will be automatically called whenever an object is created. • Like a method, constructor can be overloaded for the flexibility of the object creation. • A super class constructor can be called by a sub class object as: super(); CS170 ygao JAVA, C4 Slide 10 A constructor without any parameters public Book(){ code = ""; title = ""; price = 0.0; } A constructor with one parameter public Book(String bookCode){ code = bookCode; setTitle(bookCode); setPrice(bookCode); } A constructor with three parameters public Book(String bookCode, String bookTitle, double bookPrice){ code = bookCode; title = bookTitle; price = bookPrice; } CS170 ygao JAVA, C4 Slide 11 How to create an object in one statement ClassName objectName = new ClassName(optionalArguments); An example with no arguments Book book = new Book(); An example with one literal argument Book book = new Book("WARP"); An example with one variable argument Book book = new Book(code); An example with three arguments Book book = new Book(code, title, price); CS170 ygao JAVA, C4 Slide 12 set methods • In OOP, particularly in Java, set() means to set object’s member data • set() usually has void return and takes argument(s) to set the member data • set() also checks the validity of the data before it sets • Use meaningful name for a set() method A set method with one parameter public void setTitle(String bookCode){ if (bookCode.equalsIgnoreCase("WARP")) title = "War and Peace"; else if (bookCode.equalsIgnoreCase("MBDK")) title = "Moby Dick"; else title = "Not Found"; } CS170 ygao JAVA, C4 Slide 13 get methods • In OOP, particularly in Java, get() means to return one of object’s member data • get() usually has a return type and takes no argument • Use meaningful name for a get() method A get method that returns a String object public String getTitle(){ return title; } A get method that returns a double type public double getPrice(){ return price; } CS170 ygao JAVA, C4 Slide 14 Complete Example Analysis The BookOrder class import java.text.*; public class BookOrder{ private Book book; //Book class defined before in slide 7 & 8 private int quantity; private double total; public BookOrder(String bookCode, int orderQuantity){ book = new Book(bookCode); quantity = orderQuantity; setTotal(); } public void setTotal(){ total = quantity * book.getPrice(); } public Book getBook(){ return book; } CS170 ygao JAVA, C4 Slide 15 Complete Example Analysis (continue) The BookOrder class (continued) public int getQuantity(){ return quantity; } public double getTotal(){ return total; } public String toString(){ NumberFormat currency=NumberFormat.getCurrencyInstance(); String orderString = "Code: " + book.getCode() + "\n" + "Title: " + book.getTitle() + "\n" + "Price: " + currency.format(book.getPrice()) + "\n" + "Quantity: " + quantity+ "\n" + "Total: " + currency.format(total) + "\n"; return orderString; } } CS170 ygao JAVA, C4 Slide 16 Complete Example Analysis (continue) The code for the driver program BookOrderApp class import javax.swing.JOptionPane; public class BookOrderApp{ public static void main(String[] args){ String choice = ""; try{ while (!(choice.equalsIgnoreCase("x"))){ String code = JOptionPane.showInputDialog( "Enter a book code:"); String inputQuantity = JOptionPane.showInputDialog( "Enter a quantity:"); int quantity = parseQuantity(inputQuantity); BookOrder bookOrder = new BookOrder(code,quantity); String message = bookOrder.toString() + "\n" + "Press Enter to continue or enter 'x' to exit:"; choice = JOptionPane.showInputDialog(null, message, "Book Order", JOptionPane.PLAIN_MESSAGE); }//end while catch(NullPointerException e){ System.exit(0); } System.exit(0); } CS170 ygao JAVA, C4 Slide 17 Complete Example Analysis (continue) The code for the driver program (continued) private static int parseQuantity(String quantityString){ int quantity = 0; boolean tryAgain = true; while(tryAgain){ try{ quantity = Integer.parseInt(quantityString); while (quantity <= 0){ quantityString = JOptionPane.showInputDialog( "Invalid order total. \n" + "Please enter a positive number: "); quantity = Integer.parseInt(quantityString); } tryAgain = false; } catch(NumberFormatException e){ quantityString = JOptionPane.showInputDialog( "Invalid quantity.\n" + "Please enter an integer."); } } return quantity; } } CS170 ygao JAVA, C4 Slide 18 Static Fields • What is a static field? – a variable that is not associated with any instance of the class, therefore it’s a class-wide field/variable/data – a variable that can be used without creation of the object – a private static field can be only use within the current class – can be constant (final), so it’s value cannot be modified; must be initialized when declaring • Why static fields? – keep tracking class-wide information – Convenient to use and save memory – Be careful data encapsulation in using static fields CS170 ygao JAVA, C4 Slide 19 How to declare static fields private static int numberOfObjects = 0; private static double majorityPercent = .51; public static final int DAYS_IN_JANUARY = 31; public static final float EARTH_MASS_IN_KG = 5.972e24F; A class that contains static constants public class DateConstants{ public static final int DAYS_IN_JANUARY = 31; public static final int DAYS_IN_FEBRUARY = 27; ... } CS170 ygao JAVA, C4 Slide 20 A class that contains a static method that makes a calculation public class FinancialCalculations{ public static double calculateFutureValue(double monthlyPayment, int months, double monthlyInterestRate){ int i = 1; double futureValue = 0; while (i <= months) { futureValue = (futureValue + monthlyPayment) * (1 + monthlyInterestRate); i++; } return futureValue; } } CS170 ygao JAVA, C4 Slide 21 A class that contains a static variable and a static method public class BookOrder{ private Book book; private int quantity; private double total; private static int orderObjectCount = 0; public BookOrder(String bookTitle, int bookQuantity){ book = new Book(bookTitle); quantity = bookQuantity; setTotal(); orderObjectCount++; } public static int getOrderObjectCount(){ return orderObjectCount; } ... CS170 ygao JAVA, C4 Slide 22 The syntax for calling a static field or method className.fieldName className.methodName(optionalArgumentList) CS170 ygao JAVA, C4 Slide 23 How to call static fields From the Java API Math.PI Math.E JOptionPane.INFORMATION_MESSAGE JOptionPane.PLAIN_MESSAGE From a user-defined class DateConstants.DAYS_IN_JANUARY CS170 ygao JAVA, C4 Slide 24 How to call static methods From Java classes String inputQuantity = JOptionPane.showInputDialog( "Enter a quantity:"); int quantity = Integer.parseInt(inputQuantity); From user-defined classes double futureValue = FinancialCalculations.calculateFutureValue( monthlyPayment, months, monthlyInterestRate); int orderCount = BookOrder.getOrderObjectCount(); CS170 ygao JAVA, C4 Slide 25 Static Initialization Block • what is a static initialization block? – a block of code in a class starting with keyword static – the block will be automatically executed when any method of the class is called first time • why static initialization blocks? – used when a static object/field cannot be initialized by a single statement – ensure the object/filed is ready/available to the rest of the methods in the class starting at the point of any method in the class that is called CS170 ygao JAVA, C4 Slide 26 The syntax for coding a static initialization block public class className{ any field declarations static{ any initialization statements } the rest of the class CS170 ygao JAVA, C4 Slide 27 Simple Example of Static Block 1. public class TestStaticApp{ 2. private static int y; 3. //private int x = 0; //illigal to delcare regular variable here in app 4. 5. 6. 7. 8. static { y = 99; //declaring a static varaible //static initialization block //initializing the static variable } public static void main(String[] args){ System.out.println(“Output from main()"); 9. test(); // calling a method 10. } 11. 12. 13. public static void test() //must be static method in app { System.out.println("static field value in test():" + y); 14. } 15. } CS170 ygao JAVA, C4 Slide 28 A class that uses a static initialization block public class BookDB{ private static Connection connection; static{ try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String url = "jdbc:odbc:MurachBooks"; String user = "Admin"; String password = ""; connection = DriverManager.getConnection(url, user, password); } catch (ClassNotFoundException e){ System.err.println("Driver not found."); } catch (SQLException e){ System.err.println("Error connecting to database."); } } CS170 ygao JAVA, C4 Slide 29 A class that uses a static initialization block (continued) // other static methods that use the Connection object public static void close(){} public static void addRecord(Book book){} public static void updateRecord(Book book){} public static void deleteRecord(String bookCode){} public static Book findOnCode(String bookCode){} } CS170 ygao JAVA, C4 Slide 30 Packages • what is a package? – is used to organize the classes both API and programmer defined classes • why package? – is able programs to import classes as API – provides convention for unique class names to avoid the name conflict CS170 ygao JAVA, C4 Slide 31 Examples of package names Internet domain Package name Subdirectory path java.sun.com com.sun.java.text \com\sun\java\text murach.com com.murach.orders \com\murach\orders Other examples of package names CS170.ygao CS170 ygao JAVA, C4 ygao.CS170.classes \ygao\CS170\classes Slide 32 How to code a package statement package com.murach.orders; How to compile the package CS170 ygao JAVA, C4 Slide 33 How to make a package available to any class in your program 1. Start the command prompt and navigate to the root directory that holds your classes. 2. Use the jar command to create a JAR file for the *.class file or files. 3. Move the JAR file to the c:\jdk1.3\jre\lib\ext directory. CS170 ygao JAVA, C4 Slide 34 Syntax for creating a JAR file for a package c:\anydirectory>jar cvf JARFilename.jar classDirectory\*.class Example c:\java>jar cvf orders.jar com\murach\orders\*.class Result CS170 ygao JAVA, C4 Slide 35 How to make a package available to other classes import packageName; Example import com.murach.orders.*; CS170 ygao JAVA, C4 Slide 36 javadoc tool • what is javadoc tool? – allows you to create documentation for your classes in the same way java API does – is a command in JDK that does the documentation • why javadoc? – create professional-like documentation – Other programmers can use to learn about the fields, constructors, and methods in the classes CS170 ygao JAVA, C4 Slide 37 Code from the Book class with javadoc comments /******************************************************* * The <code>Book</code> class represents a book and is * used by the <code>BookOrder</code> class. **********************************************************/ public class Book{ private String code; private String title; private double price; /******************************************************* * Constructs a Book object from a book code. *******************************************************/ public Book(String bookCode){ code = bookCode; setTitle(bookCode); setPrice(bookCode); } CS170 ygao JAVA, C4 Slide 38 HTML tags for Java documentation HTML tags Description <code></code> Displays all text between these tags with a special font. CS170 ygao JAVA, C4 Slide 39 How to generate the API documentation for a class c:\programDirectory> javadoc –d documentationDirectory ClassNameList Examples c:\java\com\murach\orders> javadoc –d c:\java\docs Book.java c:\java\com\murach\orders> javadoc –d c:\java\docs Book.java BookOrder.java c:\java\com\murach\orders> javadoc –d c:\java\docs *.java CS170 ygao JAVA, C4 Slide 40 The documentation that’s generated for the Book class CS170 ygao JAVA, C4 Slide 41