What is messaging in OOP

Objects interact by sending and receiving messages. A message is a request to perform an action, followed by a set of arguments that may be needed when performing an action. In OOP, sending a message (calling a method) is the only way to transfer control to an object. If an object is to "reply" to this message, then it must have a method corresponding to the message. Also, objects, using their methods, can themselves send messages to other objects. Messaging is done with dynamic calls, resulting in extreme late binding.

Let's say you want to create a physical model describing colliding balls of different sizes. The traditional approach to solving this problem is approximately the following: a set of data describing each ball (for example, its coordinates, mass and acceleration) is determined; each ball is assigned a unique identifier (for example, an array is organized, the index value of which corresponds to the ball number), which will distinguish each of the balls from all the others. Finally, a subroutine is written called, say, bounce; this procedure should, based on the ball number and its initial parameters, modify the data describing the ball accordingly. In contrast to the traditional approach, the object-oriented version of the program models each of the balls by means of an object. In this case, the object corresponding to a specific ball contains not only its parameters, but also the entire code describing the behavior of the ball under various interactions. So, each ball will have its own bounce() method. Instead of calling bounce with an argument defining, say, ball #3, you would need to send a message to the ball #3 object telling it to perform a collision.


Read also:


Comments

Popular posts from this blog

Methods for reading XML in Java

XML, well-formed XML and valid XML

ArrayList and LinkedList in Java, memory usage and speed