cs170 ygao java, c4slide 1. cs170 ygao java, c4slide 2

41
CS170 ygao JAVA, C4 Slide 1 C hapter4 How to w rite object-oriented program s

Upload: bernice-weaver

Post on 17-Jan-2016

230 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 1

Chapter 4

How to writeobject-oriented programs

Page 2: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 2

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 thatdocumentation.

Page 3: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 3

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

Page 4: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 4

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();

Page 5: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 5

A class diagram for the Book class

class

attributes

operations

+setTitle(code: S tring)+setPrice(code: S tring)+getCode(): S tring+getTitle(): S tring+getPrice(): double

-code: S tring-title: S tring-price : double

Book name

/member data

/ methods

Page 6: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 6

The relationship between a class and its objects

-code: S tring-title: S tring-price: double

Book

-code = "W ARP"-title = "W ar and Peace"-price = 14.95

book1

-code = "MBDK"-title = "Moby D ick"-price = 12.95

book2

Note: Diagrams do not include methods, just for demo

Page 7: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 7

The Book classpublic class Book{ private String code; private String title; private double price;

public Book(String bookCode){ code = bookCode; setTitle(bookCode); setPrice(bookCode); }

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"; }

Instance variables/memberdata

Constructor

Method

Page 8: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 8

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; }

public String getTitle(){ return title; }

public double getPrice(){ return price; }}

More methods

Page 9: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 9

The syntax for declaring instance variablespublic|private|protected primitiveType|ClassName variableName;

Examplesprivate double price;

private int quantity;

private String title;

private Book bookObject;

Page 10: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 10

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();

Page 11: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 11

A constructor without any parameterspublic Book(){ code = ""; title = ""; price = 0.0;}

A constructor with one parameterpublic Book(String bookCode){ code = bookCode; setTitle(bookCode); setPrice(bookCode);}

A constructor with three parameterspublic Book(String bookCode, String bookTitle, double bookPrice){ code = bookCode; title = bookTitle; price = bookPrice;}

Page 12: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 12

How to create an object in one statementClassName objectName = new ClassName(optionalArguments);

An example with no argumentsBook book = new Book();

An example with one literal argumentBook book = new Book("WARP");

An example with one variable argumentBook book = new Book(code);

An example with three argumentsBook book = new Book(code, title, price);

Page 13: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 13

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"; }

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

Page 14: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 14

A get method that returns a String objectpublic String getTitle(){ return title;}

A get method that returns a double typepublic double getPrice(){ return price;}

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

Page 15: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 15

The BookOrder classimport 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; }

Complete Example Analysis

Page 16: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 16

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; }}

Complete Example Analysis (continue)

Page 17: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 17

The code for the driver program BookOrderApp classimport 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); }

Complete Example Analysis (continue)

Page 18: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 18

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; } }

Complete Example Analysis (continue)

Page 19: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 19

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

Page 20: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 20

How to declare static fieldsprivate 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 constantspublic class DateConstants{ public static final int DAYS_IN_JANUARY = 31; public static final int DAYS_IN_FEBRUARY = 27; ...}

Page 21: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 21

A class that contains a static method that makes acalculationpublic 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; }}

Page 22: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 22

A class that contains a static variable and a staticmethodpublic 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; } ...

Page 23: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 23

The syntax for calling a static field or methodclassName.fieldName

className.methodName(optionalArgumentList)

Page 24: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 24

How to call static fieldsFrom the Java APIMath.PI

Math.E

JOptionPane.INFORMATION_MESSAGE

JOptionPane.PLAIN_MESSAGE

From a user-defined classDateConstants.DAYS_IN_JANUARY

Page 25: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 25

How to call static methodsFrom Java classesString inputQuantity = JOptionPane.showInputDialog( "Enter a quantity:");int quantity = Integer.parseInt(inputQuantity);

From user-defined classesdouble futureValue = FinancialCalculations.calculateFutureValue( monthlyPayment, months, monthlyInterestRate);

int orderCount = BookOrder.getOrderObjectCount();

Page 26: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 26

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

Page 27: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 27

The syntax for coding a static initialization blockpublic class className{ any field declarations

static{ any initialization statements }

the rest of the class

Page 28: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 28

Simple Example of Static Block 1. public class TestStaticApp{

2. private static int y; //declaring a static varaible

3. //private int x = 0; //illigal to delcare regular variable here in app

4. static { //static initialization block5. y = 99; //initializing the static variable6. }7. public static void main(String[] args){8. System.out.println(“Output from main()");

9. test(); // calling a method

10. }

11. public static void test() //must be static method in app12. {13. System.out.println("static field value in test():" + y);

14. }15. }

Page 29: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 29

A class that uses a static initialization blockpublic 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."); } }

Page 30: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 30

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){}}

Page 31: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 31

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

Page 32: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 32

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 ygao.CS170.classes \ygao\CS170\classes

Page 33: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 33

How to code a package statementpackage com.murach.orders;

How to compile the package

Page 34: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 34

How to make a package available to any class inyour program1. 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.

Page 35: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 35

Syntax for creating a JAR file for a packagec:\anydirectory>jar cvf JARFilename.jarclassDirectory\*.class

Examplec:\java>jar cvf orders.jar com\murach\orders\*.class

Result

Page 36: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 36

How to make a package available to other classesimport packageName;

Exampleimport com.murach.orders.*;

Page 37: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 37

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

Page 38: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 38

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); }

Page 39: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 39

HTML tags for Java documentationHTML tags Description

<code></code> Displays all text between these tags with a special font.

Page 40: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 40

How to generate the API documentation for a classc:\programDirectory>javadoc –d documentationDirectory ClassNameList

Examplesc:\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

Page 41: CS170 ygao JAVA, C4Slide 1. CS170 ygao JAVA, C4Slide 2

CS170 ygao JAVA, C4 Slide 41

The documentation that’s generated for the Book class