22d72ad6b3ea6d33b92fe44f0c4d09cd.ppt
- Количество слайдов: 49
5. Object-Oriented Design and Programming 5. 1 Using Objects 5. 2 Developing Java Classes 5. 3 The Quick. Food 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 to. Upper. Case • Replace. java • String. Mutation. java (extra) • Reverse. java (extra)
length () to. Upper. Case() index. Of(‘a’) // other services Figure 5. 1 A String object (for “Java is fun”)
length () to. Lower. Case() index. Of(‘a’) // other services Figure 5. 2 A String object (for “JAVA IS FUN”)
public char. At(int index) character at the specified index public int compare. To(String another. String) 0 if equal to another. String negative if less positive if greater public boolean equals(Object an. Object) true for equal Strings public int index. Of(char ch) index of first occurrence of ch public int index. Of(char ch, int from) index of first occurrence of ch starting at index from public int index. Of(String str) index of first occurrence of str public int index. Of(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 begin. Index, int end. Index) new string with characters from begin. Index to end. Index – 1 public String to. Lower. Case() returns a lowercase string public String to. Upper. Case() returns an uppercase string public String trim() removes leading and trailing whitespaces public static String value. Of(int i) creates a string from an int public static String value. Of(double d) creates a string from a double Figure 5. 3 Selected String methods(2)
Method Return value Description of return value s. char. At(6) ‘e’ The character at position 6 is an ‘e. ’ s. compare. To(“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. index. Of(‘e’) 6 The leftmost ‘e’ on the string occurs at index 6. s. index. Of(‘e’, 8) 15 The first occurrence of ‘e, ’ starting from index 8, is at index 15. s. index. Of(“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. index. Of(“us”, 11) 13 The first occurrence of “us”, starting from index 11, begins at index 13. s. index. Of(“us”, 15) -1 There is no occurrence of “us” staring at index 15. s. length() This string contains 27 characters. 27 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. to. Lower. Case() A new String with characters “java let us use objects. ” Returns a new string with all lowercase characters. s. to. Upper. Case() 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 my. String holds the reference, address, of the string int x = 4; String my. String = "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 • Parameter. Passing. java • Parameter. Tester. java
“We want a big car” 4 x a. x holds a value my String b. my. String holds a reference Figure 5. 5 Value vs. reference
Y = x; 4 5 x y 4 x int x = 4, y = 5; 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 s 1 s 4 house s 2 Figure 5. 9 s 1 == s 4 but s 1 != s 2
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 face. Value 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 face. Value 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 num 1, int num 2, String message) { int sum = num 1 + num 2; char result = message. char. At(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 • Bank. Account. java, Test. Bank. Account. java • Rational. java, Rational. Number. java (extra)
Bank. Account balance: double get. Balance deposit withdraw Figure 5. 10 The Bank. Account class
Bank. Account balance: double Bank. Account() Bank. Account(initial. Amount: double) get. Balance(): double Deposit(amount: double): void withdraw(amount: double): void Figure 5. 11 The revised Bank. Account class
: Bank. Account Balance = 0. 0 get. Balance Deposit withdraw Figure 5. 12 Result of new Bank. Account()
: Bank. Account Balance = 0. 0 get. Balance Deposit my. Account withdraw Figure 5. 13 my. Account refers to a new Bank. Account
null my. Account 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 my. Account. deposit(100. 0), this refers to the current object, i. e. my. Account. • 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 index. Of(char c); public int index. Of(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, Test. Acct. java • My. Class. java, Count. Instances. java (extra)
transactions Acct class balance my. Acct object your. Acct object Figure 5. 15 The difference between class and instance variables
The Quick. Food Example • Quick. Food. 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
a. Customer a. Waiter take order make burger serve soda make fries serve burger serve fries pay Figure 5. 17 A sequence diagram for a food order a. Cook
a. Customer place order a. Waiter a. Cook 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 • Test. Person. 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 to. String - returns a string representation of the object • Another useful method get. Class - 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 to. String() 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 to. String() 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 get. Id() public String to. String() Figure 5. 19 Fields for the Name, Address and Person class(2)
Person Name Address id: String first: String 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
22d72ad6b3ea6d33b92fe44f0c4d09cd.ppt