Tuesday, February 23, 2010

Object Oriented Programming: The Object

The Object

What is an Object?

To define objects we have to define two things:
·         State (Attributes, properties)
·         Behaviour (Methods)

Real-world objects share two characteristics: They all have state and behaviour. Dogs have state (name, colour, hunger) and behaviour (barking, fetching, wagging tail).

Real-world objects vary in complexity; a desktop lamp may have only two possible states (on and off) and two possible behaviours (turn on, turn off), but a desktop radio might have additional states (on, off, volume, station) and behaviour (turn on, turn off, increase volume, decrease volume, seek, scan, and tune). You may also notice that some objects, in turn, will also contain other objects. These real-world observations all translate into the world of object-oriented programming.

The term “Object,” that gives OOP its name, refers to a conceptual object that represents an item in our program or system. This could be anything from a button on a web page or a computer file, to a real world object such as a car.

Software objects like real-world objects also consist of state and related behaviour.
·         An object stores its state (Attributes) in fields or variables
·         An object exposes its behaviour through methods (functions in some programming languages).
Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication.

Hiding the internal state and methods of a class through abstraction and requiring all interaction to be performed through an object's methods is known as encapsulation.

Bundling code into individual software objects provides a number of benefits, including:
·         Modularity: The source code for an object can be written and maintained independently of the source code for other objects. If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.
·         Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world.
Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program.

No comments: