Chapter 4: Collaboration between classes and methods (Part 1) PDF

Document Details

Uploaded by Deleted User

Badji Mokhtar University - Annaba

2024

Dr. Sarra Namane

Tags

object-oriented programming computer science classes and methods software design

Summary

This document is a course document for a 2nd year engineering class detailing the ways objects communicate with each other in object-oriented programming. It covers message passing, class association, class dependency and chain reaction messaging topics.

Full Transcript

Chapter 4: Collaboration between classes and methods (Part 1) Dr. Sarra Namane Department of Computer Science Badji Mokhtar University, Annaba Class: 2nd Year Engineering Year: 2024/2025 Introduction In Object-Oriented Programming (OOP), the way...

Chapter 4: Collaboration between classes and methods (Part 1) Dr. Sarra Namane Department of Computer Science Badji Mokhtar University, Annaba Class: 2nd Year Engineering Year: 2024/2025 Introduction In Object-Oriented Programming (OOP), the way objects interact is central to building efficient software systems. This part of the course introduces key concepts such as message passing, class association, class dependency, and chain reaction messaging. Message passing is how objects communicate by sending and receiving data or invoking methods. Class association focuses on the relationships between different classes, while class dependency explores how one class relies on another for its functionality. Chain reaction messages describe a sequence of 2 Message passing In object-oriented programming (OOP), message passing means that one object asks another object to do something by calling a method. Here are simpler examples to make this concept clearer: Example 1: Coffee Machine and Cup Coffee Machine (Object A): It can make coffee. Cup (Object B): It can hold coffee. When the coffee machine finishes making coffee, it needs to pour the coffee into the cup. The coffee machine tells the cup to hold the coffee by calling a method on it. 1. The Coffee Machine calls the method fillCup() on the 3 Message passing (2) One object (Coffee Machine) sends a message to another object (Cup) by calling a method. 4 Class association In object-oriented programming, class association is when one class knows about another class and can use its methods. This happens when objects from different classes need to communicate or work together. Let’s break this down with a simple example: Example : Teacher and Student Teacher (Class A): Can give homework. Student (Class B): Can do homework. To make sure the teacher can give homework to the student, the Teacher class must know about the Student class. The Teacher will have a reference to a Student object, so it can call the doHomework() method on it. 5 Class association (2) The Teacher knows about the Student and can call the method doHomework() on the Student object. This means the Teacher class is associated with the Student class. 6 Class Association (reference) The best way to allow two classes to communicate through message passing is by adding a reference attribute to the first class that points to the second class. This means that the first class can have its own attributes and also include a reference to another class. Thanks to this special type of reference, the first class can call methods from the second class anywhere in its code. Example: Library and Book A Library has multiple Books. 7 Class Association (reference)(2) 8 Class Association (reference)(3) The Library class is associated with the Book class through the book attribute. The Library can call the getTitle() method from the Book class because of this association. In the displayBook() method, the Library prints the title of the book it contains. This shows how one class (Library) can interact with another class (Book) by holding a reference to it, allowing the Library to access the Book’s details. "Why does the Library class hold a reference to the Book class, and not the other way around?" Great question! There’s a good reason why the Library class holds a reference to the Book class, and not the other way 9 Class Association (reference)(4) 1. Responsibility: The Library is responsible for managing Books. It "owns" or "contains" books, not the other way around. It makes sense for the Library to keep track of the books it has. A Book doesn’t need to know which library it belongs to. Its primary job is to hold information like the title, author, etc. If a Book had a reference to a Library, it would complicate the relationship because: A Book might exist in multiple libraries (in real life, a book can be found in many libraries). The Book doesn't need to know about the Library to 10 Class Association (reference)(5) 2. Ownership: In real-world relationships, the Library contains or "owns" the Book. If we think of an object-oriented design: Library is the collection that manages many books. The books are part of that collection, but they don’t "own" or manage the library. The Library can have methods to add or remove 11 Books, but a Book doesn’t control which library it Class Dependency Class dependency occurs when one class temporarily relies on another class during the execution of a method. Unlike class association, which is a more permanent relationship, a class dependency exists only for a short period, just as long as the method is running. Example: Car and Engine A Car class depends on the Engine class to start the car. But this dependency is temporary and 12 Class Dependency (2) 13 Class Dependency (3) 1.Temporary Dependency: In this example, the Car needs the Engine to start. It does not permanently hold an engine object; instead, it temporarily uses the engine to execute the startCar() method. 2. No Long-term Relationship: Once the startCar() method finishes, the Car doesn’t need the Engine anymore. This is why it’s considered a dependency and not an association. 3. Short-lived Interaction: The interaction between Car and Engine happens only during the method call, 14 Class Dependency (4) Temporary Interaction: The Printer only interacts with the Document while printing. After the printing is done, the Printer no longer needs the Document. Method Call: The Printer class receives the Document object as an argument to its printDocument() method. This dependency only lasts during the method execution. 15 Class Dependency (5) Class dependency is a short-lived relationship where one class uses another class to perform a task. The relationship ends once the method finishes executing. This kind of relationship is useful when one class doesn't need to permanently store or manage the other class but only needs it temporarily for a specific task. In both examples, the Car and Printer classes depend on the Engine and Document classes for a short period of time during method execution. 16 Chain Reaction of Messages A chain reaction of messages happens when one object sends a message to another, which then sends a message to a third, and so on. This creates a sequence where each method call triggers the next in a chain. Example: Customer Service and Support A Customer requests support, which involves multiple steps handled by different objects. 1. Customer makes a request for support. 2. SupportAgent receives the request and needs to check the IssueTracker. 3. IssueTracker logs the issue and may need to 17 Chain Reaction of Messages (2) 18 Chain Reaction of Messages (3) 1. Customer calls requestSupport() on SupportAgent. 2. SupportAgent calls handleRequest() on IssueTracker. 3. IssueTracker calls logIssue() on Database. Each step in the chain triggers the next. When Customer makes a request, it starts a chain reaction: SupportAgent processes it and triggers IssueTracker. IssueTracker logs the issue and updates the Database. 19 QCM 1.How can objects communicate with each other in an object-oriented program? A) By directly accessing each other's internal data. B) By sending messages through methods defined in their classes. C) By manipulating shared global variables. D) By modifying each other’s code directly. 20 QCM (2) 2. What happens during message passing in object-oriented programming? A) The object sends a direct message to the processor. B) One object sends a message to another, which may trigger further messages to other objects. C) The object automatically updates all other objects in the system. D) Messages are sent to a database without involving other objects. 21 QCM (3) 3. In a chain reaction of messages, what is the typical flow? A) A single object handles all messages by itself. B) Messages are passed from one object to another, creating a sequence of interactions. C) Each object handles its messages independently without any communication with other objects. D) The first object sends a message and waits for a global response. 22 QCM (4) 4.When an object is created within a method and used for communication, what happens to it after the method completes? A) It remains accessible globally. B) It is saved permanently in the heap memory. C) It is removed from memory once the method execution ends. D) It is copied to another method's memory space. 23 Ending the Conflict Between In earlier chapters, we learned that one of the key goals of Classes Object-Oriented Programming (OOP) is to reduce conflict between classes. Instead of interfering with each other's data, classes are designed to help one another by sharing services and collaborating efficiently. Let's break down this concept further, using the following points: Classes are responsible for their own data: Each class manages its own state (its internal data) and doesn't allow other classes to change it directly. Instead, if another class needs to modify that state, it must "ask" the class responsible for that data. Example: Imagine we have two classes, BankAccount and Customer. The BankAccount class manages its own balance and doesn't allow 24 Ending the Conflict Between Classes Message passing (2) and collaboration: In OOP, objects of different classes communicate by calling each other's methods. This process is called "message passing." One object sends a message (a method call) to another object, asking it to perform an action or return some data. The class receiving the message decides how to respond. Designing services and collaboration: During the design phase, we create methods (services) within classes that allow them to interact with other classes. The compiler ensures these methods are correctly 25 Java Compilation and Class Linking In Java, each class is usually stored in its own file, and these files are named according to the classes they contain (e.g., ClassA.java for a class named ClassA). When you compile one file, the Java compiler automatically detects any dependencies between classes and compiles the required classes, even if you didn’t ask it to do. This is because Java uses a dynamic linking mechanism during both compilation and execution, where dependent classes are automatically found and connected. For example, imagine you have two classes: Person.java containing the Person class. Address.java containing the Address class. The Person class depends on the Address class because each person has an address. When you compile the Person class,26Java One Class, One File In practice, and more so than in three other languages, Java enforces the separation of classes into distinct files. If you don't do it yourself when writing the source code, Java will do it for you as a result of compiling the sources. Therefore, it’s better to separate classes into different files from the start. This good practice is becoming common in all object-oriented development, regardless of 27 Unidirectional vs. Bidirectional Associations  Unidirectional Association: One class knows about and can use another class, but the second class doesn't know about or use the first class.  Bidirectional Association: Both classes know about and can use each other. 28 Example of Unidirectional vs. Bidirectional Associations (2) In a unidirectional association, the Person class knows about the Address class but not the other way around. Here, Person uses Address, but Address doesn’t use Person. 29 Example of Unidirectional vs. Bidirectional Associations (3) In a bidirectional association, both classes know about each other. 30 Example of Unidirectional vs. Bidirectional Associations (4) The Person class creates an Address object and passes itself (this) to the Address constructor. The Address class stores a reference to the Person object and can access it if 31 Compilation and Dependency In Java, when you compile Person.java, Java’s compiler automatically detects that Person depends on Address. So, it will also compile Address.java even if you only compiled Person.java. This ensures that all dependencies are handled properly. In C#, since the compiler needs to know the order of compilation, you might need to compile all files together or manage dependencies carefully. In C++, you should separate class declarations from definitions to manage dependencies. You might use forward declarations or separate header and implementation files. In Python and PHP, you can face issues with circular imports or references. For example, if Person and Address depend32 on Packages and Namespaces The purpose of packages and namespaces in programming is to organize classes and other program components into a structured hierarchy, much like how directories organize files in an operating system. This structure helps in several ways: Grouping related classes: Packages and namespaces allow you to logically group related classes together, making it easier to manage and maintain large codebases. For example, in a project with many classes, packages help by categorizing classes based on functionality, such 33 Packages and Namespaces (2) Avoiding naming conflicts: As software grows, it becomes more likely that different parts of the code may have classes or functions with the same name. Packages and namespaces prevent this by creating a unique "namespace" for each class or function. For instance, you can have multiple Employee classes in different packages without causing conflicts, because each will have a distinct package path (e.g., company.hr.Employee vs. company.finance.Employee). By organizing classes into packages (Java and Python) or namespaces (C++, C#, PHP), developers maintain a 34 QCM 1.What is the primary purpose of using packages or namespaces in object-oriented programming? a) To increase the execution speed of the program. b) To organize classes into hierarchical structures and avoid naming conflicts. c) To enable multi-threading in the program. d) To provide advanced error handling mechanisms. 35 QCM (2) 2. In which scenario would you use a bidirectional association? a) When one class needs to know about another but not vice versa b) When both classes need to send messages to each other c) When two classes are completely independent d) When classes need to be completely decoupled 36 Passing Arguments by Value in Java In Java, objects communicate by sending messages, or calling methods on each other. When one object calls a method on another, it can pass arguments to that method, which are used within the method's body. These arguments, like variables in a mathematical function, allow the method’s behavior to be fine-tuned based37 Passing Arguments by Value in Java (2) Let’s explore this with a simple example. Consider the Printer class, which has a method printPages(int pages). This method takes an integer argument, pages, which represents the number of pages to print. Here’s how it could be used: 38 Passing Arguments by Value in Java (3) 39 Passing Arguments by Value in Java (4) When the printPages method is called with totalPages as an argument, Java passes the value of totalPages to pages inside printPages. This process is called pass-by-value. In this example: 1. Pages variable starts with the value 5, which is the value of totalPages. 2. Inside the printPages method, pages is incremented by 1, so it becomes 6. 3. However, this change only affects the local variable pages inside printPages. The original variable totalPages in printDocument remains 5.40 Passing Arguments by Value in Java (5) The reason is that Java creates a temporary copy of the totalPages value when calling printPages. This temporary variable (pages) exists only for the duration of the method, and any modifications to it do not affect the original totalPages variable. 41 Passing an Object as an Argument in Java an object as Let’s explore passing an argument using a different example. Here, we have a Car class with a fuel attribute and methods to add fuel and display the fuel level. Then we create a FuelStation class, which has a method to refuel the Car. In this scenario, the FuelStation class can 42 Passing an Object as an Argument in Java (2) 43 Passing an Object as an Argument in Java (3) 44 Passing an Object as an Argument in Java (4) 45 Passing an Object as an Argument in In this code: Java (5) 1. We create a Car object (myCar) with an initial fuel level of 10. 2. The FuelStation object (station) has a method refuelCar() that takes a Car object and an integer fuelAmount as arguments. 3. When station.refuelCar(myCar, 20) is called, it directly modifies myCar by adding 20 to its fuel attribute, which permanently affects myCar. Since Java passes references to objects by value, refuelCar() can modify myCar's fuel attribute, even though it receives only a copy of the reference. This 46 Passing arguments by reference in Java In object-oriented programming, when we pass objects as arguments, they’re usually passed by reference rather than by value. This means that methods often work on the same object without creating a new copy of it each time. Languages like Java, C#, PHP 5, and Python default to this behavior, while C++ requires special handling, like using pointers or explicit references, to achieve it. This reference-passing approach is often more intuitive, since it allows different parts of a program to interact with the same object directly. Example in Java: Here, we have a class Book with a 47 Passing arguments by reference in Java (2) 48 Passing arguments by reference in Java (3) In this example, updateBookTitle receives myBook as a reference, so the changeTitle method directly changes the title attribute of the original Book object, not a copy. 49 Is Every Method a Message? In object-oriented programming, a message occurs when one object calls a method in another object, which facilitates interaction between them. However, method and message are not exactly the same. Here’s why: A message only requires knowing the method signature: its name, parameters, and return type (if any). The object calling the method doesn’t need to know what’s inside the method (the implementation). Example: Imagine a Car class with a start method. If a Person class has a driveCar method that sends the start message, the Person only needs to know that start 50 Is Every Method a Message? (2) The Person object calls car.start() by sending the start message to Car. The Person only needs to know how to call start —not what’s inside the start 51 Same Message, Multiple Methods (Polymorphism) Separating a method's signature from its implementation allows for multiple implementations of the same message. This flexibility is known as polymorphism, where different objects may respond to the same message in different ways. Example: Consider a scenario where both Dog and Cat classes have a makeSound method. They both respond to the same 52 Same Message, Multiple Methods (Polymorphism) (2) 53 Same Message, Multiple Methods (Polymorphism) (3) In this example, calling makeSound() sends the same message to both Dog and Cat, but each responds differently, demonstrating polymorphism. Message = Available Method Signature The message in object-oriented programming is only the method’s signature: the method name, return type, and parameters. The calling object (sender) doesn’t need to know the method's implementation, making the design simpler and more flexible as the program evolves. 54 Interface and Encapsulation A class's interface represents the list of method signatures that can be called from outside essentially, the "visible part" accessible to external users. However, not all methods are exposed in this way. Through encapsulation, only selected methods are granted the privilege of being called externally, which enhances the security and modularity of the class. The interface thus enables objects to communicate by defining accessible methods 55 Interface: List of Available Method Signatures For now, the main idea is that every object has a list of available messages, its interface, which other objects can use. From now on, it's the interface, not the class, that shows what services the object can provide. Objects are private and only show their interface to others. The reason for separating the class from the visible part is that the first object doesn’t need to know everything about the second object, especially if some things might change later. 56 Strictly Private Methods Private Methods When drivers start a car, they change gears and press the accelerator. They don’t need to know that pressing the pedal sends more fuel to the engine. The car handles that on its own. Similarly, when saving a file, the word processor takes care of storing it on the hard drive. The user doesn’t need to know how the word processor interacts with the hard drive. The operating system makes it easy for users 57 Globalization of Messages Message on the Internet Is a message limited to circulating in the computer's memory, as we saw in previous chapters, or can it travel across walls, borders, oceans, planets, and even entire universes? Yes, it can travel all of that and much more, as long as it finds an object to communicate with, and that object has been designed to respond to the message. There is a method that has become widely used today to connect computer objects with each other… Yes, it's the internet. Two objects can communicate through the internet, not to send funny emails or spam, but to 58 Globalization of Messages (2) For one object to communicate with another, it is important for the first object to know not only the name of the second object but also its internet address, so it can locate the computer on which the object will operate. The first object also needs 59 Globalization of Messages (3) Some complications will arise compared to sending a message within a single computer. However, the goal of distributed object mechanisms (Java-RMI, CORBA, or web services) is to make the internet aspect as transparent as possible. That means, with only a few details to learn, like object addresses and activation strategies, the development of distributed applications should be just as simple as developing local applications. 60 Distributed Computing In fact, the entire communication mechanism between objects through message sending has allowed for a rethinking of the design of distributed computer applications. The distribution of computer applications across a network means that a program running on one computer can, at a certain point, delegate part of its task to another program running on a different computer. This was already possible. However, everything has been rethought and reformulated in an object-oriented way (OO). It is no longer 61 QCM 1.What is a message in object-oriented programming? a) An instruction that modifies the state of an object. b) A function that is called in a program. c) A call to an object’s method, containing a name, arguments, and a return type. d) A data type used to store information. 62 QCM (2) 2. In object-oriented programming, what is an interface? a) The class of an object. b) The list of an object’s private methods. c) The visible part of an object, containing the signatures of methods accessible by other objects. d) A way to hide the internal state of the object. 63 QCM (3) 3. What is the difference between a method and a message? a) A method is a message with arguments. b) A method is the signature of a function, whereas a message is the call to a method. c) A method is a message sent to an object, while a message is a variable. d) A method and a message are synonymous. 64 References BERSINI, Hugues. La programmation orientée objet. Editions Eyrolles. 2010. Head First Java, Second Edition, By Kathy Sierra, Bert Bates, O'Reilly Media. Programmer en JAVA, 4ème édition, Deitel et Deitel, Les éditions Reynal Goulet. http://java.sun.com Le Programmeur JAVA 2, Lemay L, Campus Press. Au cœur de Java 2 Volume I - Notions fondamentales, Horstmann et Cornell, The Sun Microsystems Press Java Series. Programmer en Java, Claude Delannoy, Eyrolles. 65

Use Quizgecko on...
Browser
Browser