OOPs Basics With Java

Object-Oriented Programming 

In his keynote address to the 11th World Computer Congress in 1989, renowned
computer scientist Donald Knuth said that one of the most important lessons he
had learned from his years of experience is that software is hard to write!
Computer scientists have struggled for decades to design new languages and
techniques for writing software. Unfortunately, experience has shown that
writing large systems is virtually impossible. Small programs seem to be no
problem, but scaling to large systems with large programming teams can result in
$100M projects that never work and are thrown out. The only solution seems to
lie in writing small software units that communicate via well-defined interfaces and
protocols like computer chips. The units must be small enough that one
developer can understand them entirely and, perhaps most importantly, the units
must be protected from interference by other units so that programmers can code
the units in isolation.
The object-oriented paradigm fits these guidelines as designers represent complete
concepts or real world entities as objects with approved interfaces for use by
other objects. Like the outer membrane of a biological cell, the interface hides the
internal implementation of the object, thus, isolating the code from interference by
other objects. For many tasks, object-oriented programming has proven to be a
very successful paradigm. Interestingly, the first object-oriented language (called
Simula, which had even more features than C++) was designed in the 1960's, but
object-oriented programming has only come into fashion in the 1990's.
This module is broken down into three sections. First, you will find a high-level
overview that shows object-oriented programming to be a very natural concept
since it mirrors how your hunter-gatherer mind views the outside world. Second,
you will walk through object-oriented programming by example; learning to use a
simple object, examining the definition, extending the definition, and then designing
your own object. Finally, you will explore the most important concepts in
object-oriented programming: encapsulation, data hiding, messages, and
inheritance.

Encapsulation and data hiding

The first and most important design principle we can derive from our perception
of the real world is called encapsulation. When you look at an animal, you
consider it to be a complete entity--all of its behavior and attributes arise strictly
from that animal. It is an independent, completely-specified, and self-sufficient
actor in the world. You do not have to look behind a big rock looking for another
bit of functionality or another creature that is remotely controlling the animal.
Closely associated with encapsulation is the idea of data hiding. Most animals
have hidden attributes or functionality that are inaccessible or are only indirectly
accessible by other animals. The inner construction and mechanism of the human
body is not usually available to you when conversing with other humans. You can
only interact with human beings through the approved voice-recognition interface.
Bookkeeping routines such as those controlled by the autonomic nervous system
like breathing may not be invoked by other humans. Without bypassing the
approved interface, you cannot directly measure attributes such as internal body
temperature and so on.
One can conclude that we perceive objects in the world as encapsulated (selfcontained)
entities with approved interfaces that hide some implementation
behavior and attributes. From a design perspective, this is great because it limits
what you have to think about at once and makes it much easier for multiple
programmers to collaborate on a program. You can think about and design each
object independently as well as force other programmers to interact with your
objects only in a prescribed manner; that is, using only the approved interface.
You do not have to worry about other programmers playing around with the inner
workings of your object and at the same time you can isolate other programmers
from your internal changes.

The interaction of objects using polymorphism

Encapsulation and data hiding are used to define objects and their interfaces, but
what about the mechanism by which objects interact? In the real world, animals
are self-contained and, therefore, do not physically share brains. Animals must
communicate by sending signals. Animals send signals, depending on the species,
by generating sound waves such as a voice, images such as a smile, and chemicals
such as pheromones. There is no way for an animal to communicate with another
by directly manipulating the internal organs or brain of another because those
components are hidden within the other animal. Consequently, our brain is
hardwired to communicate by sending signals.
If we view the world as a collection of objects that send and receive messages,
what programming principle can we derive? At first you may suspect that a
signal or message is just a function call. Rather than manipulate the internals of an
object, you might call a function that corresponded to the signal you wanted to
send.
Unfortunately, function calls are poor analogs to real world messaging for two
main reasons. First, function calls do things backwards. You pass objects to
functions whereas you send messages to an object. You have to pass objects to
functions for them to operate on because they are not associated with a particular
object. Second, function calls are unique in that the function's name uniquely
identifies what code to run whereas messages are more generic. The receiver of a
message determines how to implement it. For example, you can tell a man and a
woman both to shave and yet they respond to the exact same message by doing
radically different things.


The relationship between objects and inheritance


Humans rely on their ability to detect similarities between objects to survive new
situations. If an animal has many of the characteristics of a snake, it is best to
leave it alone for fear of a venomous bite. In fact, some animals take advantage of
similarity detectors in other animals by mimicking more dangerous creatures; some
kingsnakes have colored bands like the deadly coral snake, although in a different
order. Similarly, we learn most easily when shown new topics in terms of how
they relate or differ from our current knowledge base. Our affinity for detecting
and using similarity supports two important ideas in the object-oriented design
model: polymorphism requires a definition of similarity to be meaningful and we
can design new objects as they differ from existing objects.


Key Object-Oriented Concepts

Objects, Classes, and Object-Oriented Programs
Summary
• An object-oriented program is a collection of objects
• Objects with same properties and behavior are
instances of the same class
• Objects have two components: state and behavior
(variables and methods)
• An object may contain other objects
• Instance variables in every object, class variables are
like global variables shared by all instances of a class
A running object-oriented program is a collection of objects that interact by
sending messages to each other like actors in a theater production. An object is an
"actor" or self-contained software unit that often corresponds to a real world
entity and, therefore, running an object-oriented program is like performing a
simulation of the real world.
Many of the objects in a running program will have the same characteristics and
conform to the same rules of behavior. Such objects are considered to be instances
of the same class. For example, there may be many instances of the class Car in
existence at any point in a running traffic simulation. An object-oriented program
is a collection of class definitions, each one wrapping up all the data and functionality associated with a single concept or entity specified in the program
design.
Consider trying to outline the definition of a car for a computer or person
unfamiliar with a car. You would note that a car has certain properties like color
and number of doors:
• color
• numberOfDoors
A car is mainly composed of an engine, a body, and four wheels:
• theEngine
• theBody
• theWheels[4]
A car has certain behavior; it can start, stop, turn left, turn right, and so on:
• start
• stop
• turnLeft
• turnRight
By adding a bit of punctuation, you can turn this outline into a Java class
definition:

class Car {
// properties
String color;
int numberOfDoors;
// contained objects (Engine,Body,Wheel defined elsewhere)
Engine theEngine;
Body theBody;
Wheel[] theWheels;
// behavior
void start() {...}
void stop() {...}
void turnLeft() {...}
void turnRight(){...}
}



This class definition is analogous to the blueprint for a car versus the car instances
themselves.
The data fields are called instance variables and the functions embedded within a
class are called methods to distinguish them from functions or procedures in nonobject-
oriented languages. Both the data fields and methods are called members of
the class. A class definition explicitly relates data and the methods that operate
on it.


Instance variables and methods


Every instance of a class has a copy of the instance variables. For example, every
instance of a Car has a color, number of doors, an engine, a body, and a set of four
wheels. If you have 10 cars in your program, you will have 10 strings, 10
integers, 10 engines, etc... Methods that operate on these instance variables are
instance methods. Method start() manipulates the engine of a single car
instance per invocation. Which car instance is determined by the method
invocation site as you will see later.


Class variables and methods


How would you count the number of cars created during the execution of the
program? In a non-object-oriented language, you would use a global variable and
increment it every time you created a new car. You cannot have global variables in
Java, but you can have class variables, which are like global variables scoped
within a class definition. There is exactly one copy of each class variable no
matter how many instances of a class you create. If you have 10 cars, they all
share a single copy of a class variable. Class variables are defined just like instance
variables, but are modified with the static keyword. The constructor for a Car
would increment the count:


class Car {
// class variables
static int count = 0;
// instance variables; properties
String color;
int numberOfDoors;
...
Car() {
count = count + 1;
...
}
}



Encapsulation and Data Hiding


Summary


• Classes encapsulate state and behavior
• Data hiding isolates internals/implementation,
providing an approved interface
• Encapsulation and data hiding:
• make team programming much easier (you
are protected from them and they are
protected from themselves)
• reduce what you have to think about at
once
• limit propagation of errors


Encapsulation


One of the best metaphors for the software object is the cell, the fundamental
biological building block. Loosely speaking, the surface of a cell is a membrane
that physically wraps the contents (encapsulation), restricts chemical exchange
with the outside environment (data hiding), and has receptors (message interface)
that receive chemical messages from other cells. Cells interact by sending chemical
messages not by directly accessing the internals of other cells.



Data hiding and interface versus implementation

Closely associated with encapsulation is the idea of data hiding where certain
variables or methods are hidden from other objects. You may prevent foreign
objects from directly manipulating the data or other implementation details of an
object just as the membrane of a cell hides its internal mechanism. Methods
labeled as public are considered part of the approved interface for using the
object; assume for now that any other members are not part of the interface. For
example, the methods of the Car class above should be part of the interface, but
the variables should not:

class Car {
// properties
String color;
int numberOfDoors;
// contained objects (Engine,Body,Wheel defined elsewhere)
Engine theEngine;
Body theBody;
Wheel[] theWheels;
// behavior
public void start() {...}
public void stop() {...}
public void turnLeft() {...}
public void turnRight(){...}
}


The code within the methods and any of the member variables could be rewritten
without affecting the interface and, hence, without forcing changes in other
objects.


 Subscribe in a reader