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
5. Object-Oriented Design and Programming 5.1 Using Objects 5.2 Developing Java Classes 5.3 The QuickFood Example 5.4 Object Composition Objectives • • • • • • Create and use objects The String class Value vs. reference Writing classes Object-oriented design Object composition Creating Objects • A variable either holds a primitive type, or it holds a reference to an object • A class name can be used as a type to declare an object reference variable, • String title; • No object has been created with this declaration • An object reference holds the address of an object • The object itself must be created separately Creating Objects • We use the new operator to create an object title = new String("Gone With The Wind"); • This calls the String constructor, which is a special method that sets up the object • Creating an object is called instantiation • An object is an instance of a particular class Creating Objects • String reference assignment can also done like this: title = "Gone With The Wind"; • This only works for the String class. Other classes must use new • Once an object has been instantiated, we can use the dot operator to invoke its methods title.length() The String Class • In java.lang package • Used to define and manipulate String objects • Each String object contains specific characters (its state) • Each String object can perform services (behaviors) such as toUpperCase • Replace.java • StringMutation.java (extra) • Reverse.java (extra) length () toUpperCase() indexOf(‘a’) // other services Figure 5.1 A String object (for “Java is fun”) length () toLowerCase() indexOf(‘a’) // other services Figure 5.2 A String object (for “JAVA IS FUN”) public char charAt(int index) character at the specified index public int compareTo(String anotherString) 0 if equal to anotherString negative if less positive if greater public boolean equals(Object anObject) true for equal Strings public int indexOf(char ch) index of first occurrence of ch public int indexOf(char ch, int from) index of first occurrence of ch starting at index from public int indexOf(String str) index of first occurrence of str public int indexOf(String str, int from) index of first occurrence of str starting at index from public int length() string length Figure 5.3 Selected String methods(1) public String substring (int beginIndex, int endIndex) new string with characters from beginIndex to endIndex – 1 public String toLowerCase() returns a lowercase string public String toUpperCase() returns an uppercase string public String trim() removes leading and trailing whitespaces public static String valueOf(int i) creates a string from an int public static String valueOf(double d) creates a string from a double Figure 5.3 Selected String methods(2) Method Return value Description of return value s.charAt(6) ‘e’ The character at position 6 is an ‘e.’ s.compareTo(“Toast”) negative integer The string referred to by s is alphabetically less than “Toast” so the return value is a negative integer. s.equals(“Java is fun”) false The string referred to by s does not have the same characters as “Java is fun” s.indexOf(‘e’) 6 The leftmost ‘e’ on the string occurs at index 6. s.indexOf(‘e’,8) 15 The first occurrence of ‘e,’ starting from index 8, is at index 15. s.indexOf(“us”) 10 The leftmost occurrence of “us” starts at index 10. Figure 5.4 Examples of string methods(1) Method Return value Description of return value s.indexOf(“us”,11) 13 The first occurrence of “us”, starting from index 11, begins at index 13. s.indexOf(“us”,15) -1 There is no occurrence of “us” staring at index 15. s.length() 27 This string contains 27 characters. s.substring(13,24) A new String with characters “use objects.” The string “use objects.” starts at index 13 and continues up to index 24. s.toLowerCase() A new String with characters “java let us use objects. ” Returns a new string with all lowercase characters. s.toUpperCase() A new String with characters “JAVA LET US USE OBJECTS. ” Returns a new string with all uppercase characters. s.trim() A new String with characters “Java lets us use objects.” Returns a new string with leading and trailing blanks removed Figure 5.4 Examples of string methods(2) Value vs. Reference • In the following, variable x holds the value 4 while myString holds the reference, address, of the string int x = 4; String myString = "We want a big car"; • A declaration like this String s; creates a reference variable without instantiating any object. • Java uses null to represent such un-initialized reference variables Value vs. Reference • Two reference variables are equal if and only if they reference the same object, i.e. they hold the same address • Never use == to check whether two objects are equal • If the type of a parameter in a method is a class, then a reference is intended • When the method is called, the parameter will be passed a reference to an object • The original object is not copied Value vs. Reference • An object argument can be changed by the called method (call by reference) • Num.java • ParameterPassing.java • ParameterTester.java “We want a big car” 4 x a. x holds a value my String b. myString holds a reference Figure 5.5 Value vs. reference int x = 4, y = 5; Y = x; 4 5 x y 4 x 4 y Figure 5.6 Assignment of an integer “soup” “fish” String s = “soup”, t = “fish”; s t “soup” “fish” t = s; s Figure 5.7 Assignment of a string t null s Figure 5.8 An object declaration without object creation house s1 s4 house s2 Figure 5.9 s1 == s4 but s1 != s2 Classes • A class is a blueprint of an object • It is the model or pattern from which objects are created • The String class was provided for us by the Java standard class library • But we can also write our own classes that define specific objects that we need • For example, we can write a Die class to simulate a die which among other things can be rolled • Die.java Data Scope • A class contains data declarations and method declarations • The scope of data is the area in the program in which that data can be used • Data declared at the class level can be used by all methods in that class • Data declared within a method, called local data, can only be used in that method Writing Methods • A method declaration specifies the code that will be executed when it is invoked (or called) • When a method is invoked, the flow of control jumps to the method and executes its code • When completed, the flow returns to the place where the methods was called and continues • The invocation may or may not return a value, depending on how the method was defined • The called method could be within the same class, in which case only the method name is needed, or it could be part of another class or object Instance data • The faceValue variable in the Die class is an instance variable because each instance of that class has its own • A class declares the type of the data, but it does not reserve any memory space for it • Every time a Die object is created, a new faceValue variable is created as well • The objects share the method definitions, but they have unique data space • So two different objects can have different states Encapsulation • You can take one of two views of an object: – internal: the structure of its data, the algorithms used by its methods – external: the interaction of the object with other objects in the program • From the external view, an object is an encapsulated entity, providing a set of specific services • These services define the interface to the object • An object is an abstraction, hiding details from the rest of the system • An object should be self-governing Encapsulation • Any changes to the objects state (its variables) should be accomplished by its methods • We should make it difficult, if not impossible, for one to "reach in" and alter another objects state • The user, or client, of an object can request its services, but it should not have to be aware of how these services are accomplished • An object can be thought of as a black box • Its inner workings are hidden to the clients, which only invokes the interface methods Method Declaration char calc(int num1, int num2, String message) { int sum = num1 + num2; char result = message.charAt(sum); return result; } • A method begins with a method header • The method header is followed by the method body • In the method header, char is the return type, calc is the method name, and the items within parentheses constitute the parameter list Method Declaration • The parameter list specifies the type and name of each parameter • The return type indicates the type of value that the methods sends back to the calling location • A method that does not return a value has a void return type • The return statement specifies the value to be returned • Its expression must conform to the return type Visibility Modifiers • Members of a class that are declared with public visibility can be accessed from anywhere • Members of a class that are declared with private visibility can only be access from inside the class • Members declared without a visibility modifier have default visibility and can be accessed by any class in the same package • There is the protected visibility which has to do with inheritance Visibility Modifiers • As a general rule, no object's data should be declared as public • Methods that provides the object's services are usually declared as public so that they can be invoked by the clients • A method created simply to assist a service method is called a support method • Support methods should not be declared as public • BankAccount.java, TestBankAccount.java • Rational.java, RationalNumber.java (extra) BankAccount balance: double getBalance deposit withdraw Figure 5.10 The BankAccount class BankAccount balance: double BankAccount() BankAccount(initialAmount: double) getBalance(): double Deposit(amount: double): void withdraw(amount: double): void Figure 5.11 The revised BankAccount class :BankAccount Balance = 0.0 getBalance Deposit withdraw Figure 5.12 Result of new BankAccount() :BankAccount Balance = 0.0 getBalance Deposit myAccount withdraw Figure 5.13 myAccount refers to a new BankAccount null myAccount Figure 5.14 An object declaration without object creation The this reference • Java uses this to refer to the current object whose method is being invoked public void deposit (double amount) { this.balance += amount; } • When invoked as myAccount.deposit(100.0), this refers to the current object, i.e. myAccount. • In this example, the this reference is optional since current object is the default object in a method Method Overloading • Method overloading is using the same name to define more than one method • Overloaded methods must have difference in their argument lists public int indexOf(char c); public int indexOf(String s); • Constructors are often overloaded • Overloaded constructors provides different ways of creating objects in the same class • A class may not have any constructors Class Variables and Methods • Class variables and class methods belong to the whole class • They are declared using the static modifier • An example is the main method of every driver class of a program • Class variables and class methods are referenced using the class name, instead of via an object • Acct.java, TestAcct.java • MyClass.java, CountInstances.java (extra) transactions Acct class balance balance myAcct object yourAcct object Figure 5.15 The difference between class and instance variables The QuickFood Example • QuickFood.java • We omitted the public modifier on the Customer, Waiter, and Cook classes, because at most one public class may appear in any file • Reusable classes should be declare as public and placed in a separate file • UML (Unified Modeling Language) class design shows association between classes • An association represents a relationship between instances of the associated classes Customer Waiter Cook Figure 5.16 A class diagram aCustomer aWaiter take order make burger serve soda make fries serve burger serve fries pay Figure 5.17 A sequence diagram for a food order aCook aCustomer place order aWaiter aCook take order make burger take soda order serve burger serve soda take fries order make fries done serve fries pay Figure 5.18 A revised sequence diagram for a food order Object Composition • An object can contain other objects • Composition models the Has-A relationship • Inheritance models the Is-A relationship which will be covered later • Composition and inheritance are the major mechanism to build new classes using those already defined • Name.java, Address.java, Person.java • TestPerson.java The Object Class • The Object class is the granddaddy of all classes • Some of its methods are usually redefined to fit the purpose of the class being defined clone - creates and returns a copy of this object equals - indicates whether two objects are equal finalize - called by the garbage collector when it is determined that the object is not referenced toString - returns a string representation of the object • Another useful method getClass - returns the runtime class of the object Name private String first private char initial private String last public Name(String f, String l) public Name(String f, char i, String l) public String toString() Address private String street private String city private String state private String zip public Address(String st, String cy, String se, String zp) public String toString() Figure 5.19 Fields for the Name, Address and Person class(1) Person private String id private Name name private Address address public Person(String i, Name a, Address a) public String getId() public String toString() Figure 5.19 Fields for the Name, Address and Person class(2) Person id: String Name first: String Address id: String name: Name initial: char name: Name address: Address last: String address: Address zip: String Figure 5.20 Composition: the Name, Address and Person class :Name first: “Wolfgang” initial: ‘A’ composer last: “Mozart” Figure 5.21 An instance of Name