1 / 67

Understanding Object-Oriented Design in Java

Chapter 8 delves into static class members, object passing, and aggregation concepts in Java. Learn about how to write equals methods, use toString method, and collaborate classes effectively. Discover the power of static fields and methods for efficient coding practices.

toi
Download Presentation

Understanding Object-Oriented Design in Java

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. Chapter Topics Chapter 8 discusses the following main topics: Static Class Members Passing Objects as Arguments to Methods Returning Objects from Methods The toString method Writing an equals Method Methods that Copy Objects

  2. Chapter Topics Chapter 8 discusses the following main topics: Aggregation The this Reference Variable Enumerated Types Garbage Collection Focus on Object-Oriented Design: Class Collaboration

  3. The length Field & The length Method – recalled from #7 An array of String objects can be created: String[] names = { "Bill", "Susan", "Steven", "Jean ", " Kaye "}; • Arrays have a final field named length of 5. • String objects have a method named length. • To display the length of each string held in a String array: for (inti = 0; i < names.length; i++) System.out.println(names[i].length()); • An array’s length member is a field • You do not write a set of parentheses after its name. • A String’s length is a method • You do write the parentheses after the name of the String class’s length method.

  4. Review of Instance Fields and Methods Each instance of a class has its own copy of instance variables. Example: The Rectangle class defines a length and a width field. Each instance of the Rectangle class can have different values stored in its length and width fields. Instance methods require that an instance of a class be created in order to be used. As an example, box2.getLength() Instance methods typically interact with instance fields or calculate values based on those fields. Rectangle box1 = new Rectangle(12.0, 3.0); Rectangle box2 = new Rectangle(3.0, 12.1);

  5. Static Class Members Static fields and static methodsdo not belong to a single instance of a class. To invoke a static method or use a static field, the class name, rather than the instance name, is used. Example: double val = Math.sqrt(25.0); names.length names[i].length() As an example, Rectangle.getCountBoxesCreatedstatic() Class name Static method

  6. Static Fields Class fields are declared using the static keyword between the access specifier and the field type. private static int instanceCount = 0; The field is initialized to 0 only once, regardless of the number of times the class is instantiated. Primitive static fields are initialized to 0 if no initialization is performed. Examples: Countable.java, StaticDemo.java This static field, instanceCount has a value 0 which is belonged to all created instances of a class.

  7. Static Fields instanceCount field (static) 3 Object1 Object2 Object3 This static method, getInstanceCount public static intgetInstanceCount(){ return instanceCount; }

  8. Static Methods Methods can also be declared static by placing the static keyword between the access modifier and the return type of the method. public static double milesToKilometers(double miles) {…} When a class contains a static method, it is not necessary to create an instance of the class in order to use the method. double kilosPerMile = Metric.milesToKilometers(1.0); Examples: Metric.java, MetricDemo.java This static method, getInstanceCount get the current value of the static field instanceCount, which is belonged to all created instances of a class.

  9. Static Methods Static methods are convenient because they may be called at the class level. They are typically used to create utility classes, such as the Math class in the Java Standard Library. Static methods may not communicate with instance fields, only static fields.

  10. publicclass Countable { privatestaticintinstanceCount = 0; privateintinstanceCountNonStatic = 0; public Countable() { instanceCount++; instanceCountNonStatic++; } publicintgetInstanceCount() { returninstanceCount; } publicstaticintgetInstanceCt() { returninstanceCount; } publicintgetInstanceCountNonStatic() { returninstanceCountNonStatic; } }

  11. publicclass ClassnObject_8_01_staticCountable { publicstaticvoid main(String[] args) { intobjectCount; intobjectCountNonStatic; //Create four instances of the Countable class Countable object01= new Countable(); objectCount = object01.getInstanceCount(); System.out.println("\nat Point 900: " + "Use static getInstance method"); displayObjectCount(objectCount); Countable object02 = new Countable(); Countable object03 = new Countable(); objectCount = object03.getInstanceCount(); System.out.println("\nat Point 903: " + "Use static getInstance method"); displayObjectCount(objectCount); //to be continued

  12. //Get the number of instance from the class's static field //via static getInstnaceCount method. objectCount = Countable.getInstanceCt(); System.out.println("\nat Point 9: " + "Use static getInstanceCt method"); displayObjectCount(objectCount); objectCount = object01.getInstanceCount(); System.out.println("\nat Point 909: " + "Use static getInstance method"); displayObjectCount(objectCount); objectCountNonStatic = object01.getInstanceCountNonStatic(); System.out.println(objectCountNonStatic + " instances of the class was created at Pt 01."); //Get the number of instance from the class's static field objectCount = object03.getInstanceCount(); displayObjectCount(objectCount); //to be continued

  13. objectCountNonStatic = object03.getInstanceCountNonStatic(); System.out.println(objectCountNonStatic + " instances of the class was created at Pt 03."); //objectCountNonStatic = //Countable.getInstanceCountNonStatic(); //no class.nonstaticmethod objectCountNonStatic = object03.getInstanceCountNonStatic(); System.out.println(objectCountNonStatic + " instances of the class was created at Pt 03."); objectCountNonStatic = object03.getInstanceCount(); System.out.println(objectCountNonStatic + " instances of the class was created at Pt 03."); //objectCountNonStatic = Countable.getInstanceCount(); //no class.nonstaticmethod objectCountNonStatic = Countable.getInstanceCt(); System.out.println(objectCountNonStatic + " instances of the class was created at Pt 03a."); } publicstaticvoid displayObjectCount(intnumberObjectCount) { System.out.println("\n" + numberObjectCount + " instances of the class was created."); } }

  14. at Point 900: Use static getInstance method 1 instances of the class was created. at Point 903: Use static getInstance method 3 instances of the class was created. at Point 9: Use static getInstanceCt method 3 instances of the class was created. at Point 909: Use static getInstance method 3 instances of the class was created. 3 instances of the class was created at Pt 00. 1 instances of the class was created at Pt 01. 3 instances of the class was created. 3 instances of the class was created. 1 instances of the class was created at Pt 03. 1 instances of the class was created at Pt 03. 3 instances of the class was created at Pt 03. 3 instances of the class was created at Pt 03a.

  15. Passing Objects as Arguments Objects can be passed to methods as arguments. Java passes all arguments by value. When an object is passed as an argument, the value of the reference variable is passed. The value of the reference variable is an address or reference to the object in memory. A copy of the object is not passed, just a pointer to the object. When a method receives a reference variable as an argument, it is possible for the method to modify the contents of the object referenced by the variable.

  16. Passing Objects as Arguments Examples:PassObject.javaPassObject2.java A Rectangle object length: width: 12.0 5.0 displayRectangle(box); Address public static void displayRectangle(Rectangle r) { // Display the length and width. System.out.println("Length: " + r.getLength() + " Width: " + r.getWidth()); } Address

  17. Returning Objects From Methods Methods are not limited to returning the primitive data types. Methods can return references to objects as well. Just as with passing arguments, a copy of the object is not returned, only its address. See example: ReturnObject.java Method return type:BankAccount account1 = getAccount(); … public static BankAccountgetAccount() { … return new BankAccount(balance); }

  18. Returning Objects from Methods public static void main(String[] args) { BankAccount account; account = getAccount(); } A BankAccount Object balance: 3200.0 address public static BankAccount getAccount() { double balance = 3200.00; … return new BankAccount(balance); }

  19. The toString Method The toString method of a class can be called explicitly: Stock xyzCompany = new Stock ("XYZ", 9.62); System.out.println(xyzCompany.toString()); However, the toString method does not have to be called explicitly but is called implicitly whenever you pass an object of the class to println or print. Stock xyzCompany = new Stock ("XYZ", 9.62); System.out.println(xyzCompany); public class Stock { private String symbol; private double sharePrices; public Stock(String sym, double price){ symbol = sym; sharePrices = price; } … public String toString(){ String str = “Trading symbol: ” + symbol + “\nShare price: ” + sharePrice; return str; } }

  20. The toString Method The toString method of a class can be called explicitly: Stock xyzCompany = new Stock ("XYZ", 9.62); System.out.println( xyzCompany.toString()); However, the toString method does not have to be called explicitly but is called implicitly whenever you pass an object of the class to println or print. public static void main(String[] args) { Stock xyzCompany = new Stock ("XYZ", 9.62); System.out.println(xyzCompany); }

  21. The toString method The toString method is also called implicitly whenever you concatenate an object of the class with a string. Stock xyzCompany = new Stock ("XYZ", 9.62); System.out.println("The stock data is:\n" + xyzCompany);

  22. The toString Method All objects have a toString method that returns the class name and a hash of the memory address of the object. We can override the default method with our own to print out more useful information. Examples: Stock.java, StockDemo1.java

  23. The equals Method When the == operator is used with reference variables, the memory address of the objects are compared. The contents of the objects are not compared. All objects have an equals method. The default operation of the equals method is to compare memory addresses of the objects (just like the == operator).

  24. The equals Method When the == operator is used with reference variables, the memory address of the objects are compared. The contents of the objects are not compared. All objects have an equals method. The default operation of the equals method is to compare memory addresses of the objects (just like the == operator). String name1 = “James”; // String name1 = new String(“James”); String name2 = “James”; // String name2 = new String(“James”); if (name1 == name2) //ans: true!//false! James James System.out.println(“true!” + “ ” + name1 + “ ” + name2); else System.out.println(“false!”); if (name1.equals(name2)) //James and James are the same. {System.out.println(name1 + “ and ” + name2 + “are the same.”);} else {System.out.println(name1 + “ and ” + name2 + “are NOT the same.”);}

  25. The equals Method The Stock class has an equals method. If we try the following: Stock stock1 = new Stock("GMX", 55.3); Stock stock2 = new Stock("GMX", 55.3); if (stock1 == stock2) // This is a mistake. System.out.println("The objects are the same."); else System.out.println("The objects are not the same."); only the addresses of the objects are compared.

  26. The equals Method Instead of using the == operator to compare two Stock objects, we should use the equals method. Now, objects can be compared by their contents rather than by their memory addresses. See example: StockCompare.java public boolean equals(Stock object2) { boolean status; if(symbol.equals(Object2.symbol) && sharePrice == Object2.sharePrice) status = true; else status = false; return status; }

  27. Methods That Copy Objects There are two ways to copy an object. You cannot use the assignment operator to copy reference types Reference only copy This is simply copying the address of an object into another reference variable. Deep copy (correct) This involves creating a new instance of the class and copying the values from one object into the new object. Example: ObjectCopy.java

  28. Methods That Copy Objects There are two ways to copy an object. You cannot use the assignment operator to copy reference types Reference only copy This is simply copying the address of an object into another reference variable. Deep copy (correct) This involves creating a new instance of the class and copying the values from one object into the new object. Example: ObjectCopy.java Reference Copy Rectangle rectBox1 = new Rectangle(12.0, 14.0); Rectangle rectBox2 = rectBox1; rectBox1 rectBox2 length : width: 12.0 14.0 address address

  29. Methods That Copy Objects There are two ways to copy an object. You cannot use the assignment operator to copy reference types Reference only copy This is simply copying the address of an object into another reference variable. Deep copy (correct) This involves creating a new instance of the class and copying the values from one object into the new object. Example: ObjectCopy.java Deep Copy public Rectangle copy() { Rectangle box3Copied = new Rectangle(length, width); return box3Copies; } public static void main(String[] args){ Rectangle rectBox1 = new Rectangle(12.0, 14.0); Rectange box3; box3 = rectBox1.copy(); }

  30. Copy Constructors A copy constructor accepts an existing object of the same class and clones it public Stock(Stock object 2) { symbol = object2.symbol; sharePrice = object2.sharePrice; } // Create a Stock object Stock company1 = new Stock("XYZ", 9.62); //Create company2, a copy of company1 Stock company2 = new Stock(company1);

  31. Aggregation Creating an instance of one class as a reference in another class is called object aggregation. Aggregation creates a “has a” relationship between objects. Examples: Instructor.java, Textbook.java, Course.java, CourseDemo.java

  32. Aggregation in UML Diagrams Course TextBook - courseName : String - Instructor : Instructor - textBook : TextBook • title : String • author : String • publisher : String + Course(name : String, instr : Instructor, text : TextBook) + getName() : String + getInstructor() : Instructor + getTextBook() : TextBook + toString() : String + TextBook(title : String, author : String, publisher : String) + TextBook(object2 : TextBook) + set(title : String, author : String, publisher : String) : void + toString() : String Instructor • lastName : String • firstName : String • officeNumber : String + Instructor(lname : String, fname : String, office : String) +Instructor(object2 : Instructor) +set(lname : String, fname : String, office : String): void + toString() : String

  33. publicclass TextBook { private String title;//Title of the book. private String author;//Author's last name. private String edition;//Book edition. private String publisher;//Name of publisher. /** * This constructor initializes the title, author, * edition, publisher fields */ public TextBook(String textTitle, String auth, String edNos, String pub) { title = textTitle; author = auth; edition = edNos; publisher = pub; } //to be continued

  34. /** * The copy constructor initilaizes the object as a * copy of another TextBook object. */ public TextBook(TextBook object2) { title = object2.title; author = object2.author; edition = object2.edition; publisher = object2.publisher; } /** * The set method sets a value for each field. */ publicvoid set(String textTitle, String auth, String edNos, String pub) { title = textTitle; author = auth; edition = edNos; publisher = pub; } //to be continued

  35. public String toString() { //Create a string representing the object. String str = "Title of the textBook: " + title + "\nAuthor: " + author + "\nEdition: " + edition + "\nPublisher: " + publisher; //Return the string. return str; } } //end of class TextBook

  36. /** * This class Instructor stores data about an instructor. */ publicclass Instructor { private String firstName; private String middleName; private String lastName; private String title; private String terminatedDegreeHeld; private String officeBuilding; private String officeNumber; private String officePhoneNumber; private String emailAddress; //to be continued

  37. /** * The constructor initializes the first name, middle name, * last name, title, terminate degree held, office building, * office number for the instructor */ public Instructor(String fName, String mName, String sName, String titlePosition, String terminatedDegree, String officeBldg, String officeNos, String phoneNos, String emailAddr) { firstName = fName; middleName = mName; lastName = sName; title = titlePosition; terminatedDegreeHeld = terminatedDegree; officeBuilding = officeBldg; officeNumber = officeNos; officePhoneNumber = phoneNos; emailAddress = emailAddr; } //to be continued

  38. /** * The copy constructor initializes the object as * a copy of another Instructor object. */ public Instructor(Instructor object2) { firstName = object2.firstName; middleName = object2.middleName; lastName = object2.lastName; title = object2.title; terminatedDegreeHeld = object2.terminatedDegreeHeld; officeBuilding = object2.officeBuilding; officeNumber = object2.officeNumber; officePhoneNumber = object2.officePhoneNumber; emailAddress = object2.emailAddress; } //to be continued

  39. /** * The set method sets a value for each field. */ publicvoid setFacultyName(String fName, String mName, String sName) { firstName = fName; middleName = mName; lastName = sName; } publicvoid setFacultyTitleDegree(String titleHeld, String degreeHeld) { title = titleHeld; terminatedDegreeHeld = degreeHeld; } //to be continued

  40. publicvoidsetFacultyAccessInfo(String officeBldg, String officeNos, String officePhoneNos, String emailAddr) • { • officeBuilding = officeBldg; • officeNumber = officeNos; • officePhoneNumber = officePhoneNos; • emailAddress = emailAddr; • } • public String toString() • { • //Create a string representing the object. • String str = "First Name: " + firstName + • "\nMiddle Name: " + middleName + • "\nLast Name: " + lastName + • "\nOffice Building: " + officeBuilding + • "\nOffice Number: " + officeNumber + • "\nOffice Phone Number: " + officePhoneNumber + • "\nEmail Address: " + emailAddress; • //Return the string. • returnstr; • } • //to be continued

  41. /* public String toString() { String strAccess = "Office Building: " + officeBuilding + "Office Number: " + officeNumber + "Office Phone Number: " + officePhoneNumber + "Email Address: " + emailAddress; return strAccess; } public String toString() { String strTitleDegreeHeld = "Title: " + title + "Highest Degree Held: " + terminatedDegreeHeld; return strTitleDegreeHeld; } */ } //end of class instructor

  42. /** * This class Course stores data about a course. */ publicclass Course { private String courseNumber; //Course number. private String courseName; //Name of the course. private Instructor instructor; //The course's instructor. private TextBook textBook;//The course's textbook. /** * The constructor initializes the courseNumber, courseName, * instructor, and textBook fields. */ //to be continued

  43. /** * The constructor initializes the courseNumber, courseName, * instructor, and textBook fields. */ public Course(String cNos, String cName, Instructor instr, TextBook text) { //Assign the courseNumber. courseNumber = cNos; //Assign the courseName. courseName = cName; //Create a new Instructor object, passing instr as //an argument to the copy constructor. instructor = new Instructor(instr); //Create a new TextBook object, passing text as //an argument to the copy constructor. textBook = new TextBook(text); } //to be continued

  44. /** * getCourseNumber method */ public String getCourseNumber() { returncourseNumber; } //getCourseName method public String getCourseName() { returncourseName; } // getInstructor method public Instructor getInstructor() { //Return a copy of the instructor object. returnnew Instructor(instructor); } //to be continued

  45. /** * getTextBook method */ public TextBook getTextBook() { //Return a copy of the textBook object. returnnew TextBook(textBook); } public String toString() { //Create a string representing the object. String str = "Course number: " + courseNumber + "\nCourse name: " + courseName + "\nInstructor Information: \n" + instructor + "\nTextBook Information: \n" + textBook; //Return the string. returnstr; } } //end of TextBook

  46. publicclass ClassnObjects_8_07_Aggregation { publicstaticvoid main(String[] args) { //Create an Instructor object. Instructor faculty01 = new Instructor("Peter", "Apple", "Smith", "Professor of Computer Science", "PhD", "ETCS Building", "ET 125L", "(260) 481-6237", "smithp@ipfw.edu"); //Create a TextBook object TextBook textBookCS160 = new TextBook("Starting Out with Java", "Gaddis", "5th Edition", "Pearson"); //Create a Course object. Course courseCS160_07 = new Course("CS 160-07", "Intro to Computer Science", faculty01, textBookCS160); //Display the course information. System.out.println(courseCS160_07); } }

  47. Course number: CS 160-07 Course name: Intro to Computer Science Instructor Information: First Name: Peter Middle Name: Apple Last Name: Smith Office Building: ETCS Building Office Number: ET 125L Office Phone Number: (260) 481-6237 Email Address: smithp@ipfw.edu TextBook Information: Title of the textBook: Starting Out with Java Author: Gaddis Edition: 5th Edition Publisher: Pearson

  48. Returning References to Private Fields Avoid returning references to private data elements. Returning references to private variables will allow any object that receives the reference to modify the variable.

  49. Null References A null reference is a reference variable that points to nothing. If a reference is null, then no operations can be performed on it. References can be tested to see if they point to null prior to being used. if(name != null) { System.out.println("Name is: " + name.toUpperCase()); } Examples: FullName.java, NameTester.java

More Related