1 / 49

5. Object-Oriented Design and Programming

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.

daisyb
Download Presentation

5. Object-Oriented Design and Programming

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. 5. Object-Oriented Design and Programming 5.1 Using Objects 5.2 Developing Java Classes 5.3 The QuickFood Example 5.4 Object Composition

  2. Objectives • Create and use objects • The String class • Value vs. reference • Writing classes • Object-oriented design • Object composition

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

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

  5. 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()

  6. 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)

  7. indexOf(‘a’) length () toUpperCase() // other services Figure 5.1 A String object (for “Java is fun”)

  8. indexOf(‘a’) length () toLowerCase() // other services Figure 5.2 A String object (for “JAVA IS FUN”)

  9. Figure 5.3 Selected String methods(1)

  10. Figure 5.3 Selected String methods(2)

  11. Figure 5.4 Examples of string methods(1)

  12. Figure 5.4 Examples of string methods(2)

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

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

  15. Value vs. Reference • An object argument can be changed by the called method (call by reference) • Num.java • ParameterPassing.java • ParameterTester.java

  16. “We want a big car” 4 my String x a. x holds a valueb. myString holds a reference Figure 5.5 Value vs. reference

  17. 4 5 int x = 4, y = 5; x y Y = x; 4 4 x y Figure 5.6 Assignment of an integer

  18. “soup” “fish” String s = “soup”, t = “fish”; s t “soup” “fish” t = s; s t Figure 5.7 Assignment of a string

  19. null s Figure 5.8 An object declaration without object creation

  20. house s1 s4 house s2 Figure 5.9 s1 == s4 but s1 != s2

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

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

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

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

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

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

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

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

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

  30. 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)

  31. BankAccount balance: double getBalance deposit withdraw Figure 5.10 The BankAccount class

  32. BankAccount balance: double BankAccount() BankAccount(initialAmount: double) getBalance(): double Deposit(amount: double): void withdraw(amount: double): void Figure 5.11 The revised BankAccount class

  33. :BankAccount Balance = 0.0 getBalance Deposit withdraw Figure 5.12 Result of new BankAccount()

  34. :BankAccount Balance = 0.0 getBalance Deposit withdraw myAccount Figure 5.13 myAccount refers to a new BankAccount

  35. null myAccount Figure 5.14 An object declaration without object creation

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

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

  38. 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)

  39. transactions Acct class balance balance myAcct object yourAcct object Figure 5.15 The difference between class and instance variables

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

  41. Customer Waiter Cook Figure 5.16 A class diagram

  42. aCustomer aWaiter aCook take order make burger serve soda make fries serve burger serve fries pay Figure 5.17 A sequence diagram for a food order

  43. aCustomer aWaiter aCook place order take order make burger serve burger take soda order serve soda take fries order make fries serve fries done pay Figure 5.18 A revised sequence diagram for a food order

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

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

  46. 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)

  47. 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)

  48. Person Name Address id: String name: Name address: Address first: String initial: char last: String id: String name: Name address: Address zip: String Figure 5.20 Composition: the Name, Address and Person class

  49. :Name first: “Wolfgang” initial: ‘A’ last: “Mozart” composer Figure 5.21 An instance of Name

More Related