Message Passing
Definition
Message passing is the process by which one object communicates with another by sending a request, usually in the form of a method call, to perform a specific action or return information, while keeping the receiver’s internal data hidden.
This concept is central to object-oriented programming because it:
- promotes data hiding,
- supports encapsulation,
- allows objects to interact through well-defined interfaces,
- and reduces direct dependence on internal implementation details.
Main Content
1. Object Interaction
- Message passing is the primary way objects communicate in object-oriented systems.
- One object sends a request to another object, and the receiving object responds by executing the appropriate method.
In OOP, objects are not supposed to freely access each other’s internal data. Instead, they interact through messages. This means the communication happens through the object’s public interface, not through direct manipulation of private variables.
For example:
class Student:
def __init__(self, name):
self.name = name
def display(self):
print("Student Name:", self.name)
s = Student("Asha")
s.display() # message passed to object s
Here, s.display() is a message sent to the Student object. The object receives the message and performs the action of displaying the name.
Why this matters:
- It makes programs more modular.
- Each object has a clear role.
- Objects can be replaced or modified with minimal impact on other parts of the system.
A simple view:
Sender Object ---> Message ---> Receiver Object
The sender does not need to know how the receiver works internally.
2. Encapsulation and Data Hiding
- Message passing works closely with encapsulation by allowing access only through methods.
- The internal state of an object remains hidden, and changes happen only through controlled messages.
Encapsulation means bundling data and methods together and restricting direct access to the data. Message passing is the practical mechanism that makes this restriction useful.
For example, consider a Car object:
class Car:
def __init__(self):
self.__speed = 0
def accelerate(self, value):
self.__speed += value
def get_speed(self):
return self.__speed
The internal variable __speed is hidden. External code cannot directly change it. Instead, it sends messages such as accelerate(10) or get_speed().
This provides several benefits:
- Data remains protected from accidental misuse.
- The object can enforce rules before changing its state.
- Internal implementation can change without affecting users of the class.
Example of controlled access:
- A
BankAccountobject may reject withdrawal if the amount exceeds balance. - A
StudentRecordobject may validate marks before storing them. - A
Thermostatobject may restrict temperature values to a safe range.
Thus, message passing is not just communication; it is a controlled and safe method of interacting with hidden data.
3. Polymorphism and Dynamic Behavior
- Message passing allows different objects to respond differently to the same message.
- This supports polymorphism, where the same method name can produce different behavior depending on the object.
In object-oriented systems, different classes may implement the same method name, but each class can define its own behavior.
Example:
class Dog:
def speak(self):
print("Bark")
class Cat:
def speak(self):
print("Meow")
animals = [Dog(), Cat()]
for animal in animals:
animal.speak()
The same message speak() is sent to different objects, but each object responds in its own way.
This is powerful because:
- Code becomes flexible and extensible.
- New classes can be added without changing existing logic much.
- The same interface can support many different behaviors.
In real life:
print()may behave differently for text, numbers, or objects.draw()may work differently for circles, rectangles, and triangles.pay()may work differently for cash, card, or online payment objects.
This ability to send the same message and get different responses is one of the most important advantages of message passing.
Working / Process
1. Sender object decides to communicate
- An object identifies that it needs another object to perform some action or provide information.
- Instead of directly altering the other object’s internal state, it prepares a request.
2. Message is sent through a method call
- The sender invokes a method on the receiver object.
- This method call acts as the message.
- The sender usually supplies arguments that describe what needs to be done.
3. Receiver object processes the message
- The receiving object executes the corresponding method.
- It may update its internal data, return a value, or trigger another action.
- The sender only sees the result, not the internal procedure.
Example process:
class Account:
def __init__(self):
self.balance = 1000
def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
return "Withdrawal successful"
return "Insufficient balance"
acc = Account()
result = acc.withdraw(300)
print(result)
Process explanation:
- The object
accreceives the messagewithdraw(300). - It checks whether the withdrawal is valid.
- It changes the balance only if allowed.
- The caller gets the result string.
This can also be shown as:
User/Object A
|
| sends message: withdraw(300)
v
Object B (Account)
|
| checks balance and updates state
v
Response returned
Advantages / Applications
Improves encapsulation and security
- Internal data is protected from direct access.
- Objects control how their state is modified.
Promotes modular and maintainable code
- Each object manages its own responsibilities.
- Changes inside one class usually do not affect others if the interface stays the same.
Supports reusable and flexible systems
- The same message can be sent to different objects with different outcomes.
- This makes code easier to extend, test, and reuse in large applications.
Message passing is widely used in:
- object-oriented programming languages such as Java, Python, C++, and C#,
- graphical user interfaces, where buttons send click messages to handlers,
- distributed systems, where one service sends requests to another,
- robotics and embedded systems, where components communicate through commands,
- actor-based models, where independent entities communicate only through messages.
Practical examples:
- A login system sends a
verifyCredentials()message to an authentication object. - A drawing application sends
draw()messages to shape objects. - A shopping app sends
calculateTotal()to a cart object. - A chat system sends messages between users or services.
Because of this, message passing is essential in both software design and real-world computing systems.
Summary
- Message passing is a way for objects to communicate by sending method calls.
- It supports encapsulation by keeping internal data hidden.
- It helps objects interact flexibly and respond differently to the same request.
- Important terms to remember: object, message, method call, encapsulation, data hiding, polymorphism