Saturday, March 20, 2010

Types

JAVA, like most programming languages classifies values and expressions into types.
For e.g. String’s and int’s are types. A type basically specifies the allowed values
and allowed operations on values of that type.
Definition: A type is a set of values together with one or more operations
that can be applied uniformly to all these values.
A type system basically gives meaning to collections of bits. Because any value
simply consists of a set of bits in a computer, the hardware makes no distinction
between memory addresses, instruction code, characters, integers and floating-point
numbers. Types inform programs and programmers how they should treat those bits.
For example the integers are a type with values in the range −2, 147, 483, 648 to +
2, 147, 483, 647 and various allowed operations that include addition, subtraction, modulus
etc.
The use of types by a programming language has several advantages:
• Safety. Use of types may allow a compiler to detect meaningless or invalid code.
For example, we can identify an expression ”Hello, World” / 3 as invalid because
one cannot divide a string literal by an integer. Strong typing offers more safety.
• Optimization. Static type-checking may provide useful information to a compiler.
The compiler may then be able to generate more efficient code.
• Documentation. Types can serve as a form of documentation, since they can
illustrate the intent of the programmer. For instance, timestamps may be a
subtype of integers – but if a programmer declares a method as returning a
timestamp rather than merely an integer, this documents part of the meaning
of the method.
• Abstraction. Types allow programmers to think about programs at a higher
level, not bothering with low-level implementation. For example, programmers
can think of strings as values instead of as a mere array of bytes.
There are fundamentally two types in JAVA: primitive types and objects types i.e.
any variable you declare are either declared to be one of the primitive types or an
object type. int, double and char are the built-in, primitive types in JAVA.
The primitive types can be used in various combinations to create other, composite
types. Every time we define a class, we are actually defining a new type. For example,
the Student class defined above introduces a new type. We can now use this type like
any other type: we can declare variables to be of this type and we can use it as a type
for parameters of methods.
Before a variable can be used, it must be declared. A declaration gives a variable
a name, a type and an initial value for e.g. int x = 8 declares x to be of type int. All
objects that we declare also have to be of a specified type—the type of an object is the
class from which it is created. Thus, when we declare objects we state the type like
so: Student st = new Student();. This statement declares the variable st to be of
type Student. This statement creates a new object of the specified type and runs the
Student constructor. The constructor’s job is to properly initialize the object.
The String type is another example of an object type. Student and String are
composite types and give us the same advantages as the built-in types. The ability to
create our own types is a very powerful idea in modern languages.
When declaring variables, we can assign initial values. If you do not specify initial
values, the compiler automatically assigns one: Instance variables of numerical
type (int, double, etc.) are automatically initialized to zero; boolean variables are
initialized to false; and char variables, to the Unicode character with code number
zero. The default initial value of object types is null.

Classes

In object-oriented software, it’s possible to have many objects of the same kind that
share characteristics: rectangles, employee records, video clips, and so on. A class is
a software blueprint for objects. A class is used to manufacture or create objects.
The class declares the instance variables necessary to contain the state of every
object. The class would also declare and provide implementations for the instance
methods necessary to operate on the state of the object.
Definition: A class is a blueprint that defines the variables and the methods
common to all objects of a certain kind.

After you’ve created the class, you can create any number of objects from that
class.
A class is a kind of factory for constructing objects. The non-static parts of the
class specify, or describe, what variables and methods the objects will contain. This
is part of the explanation of how objects differ from classes: Objects are created and
destroyed as the program runs, and there can be many objects with the same structure,
if they are created using the same class.

Messages

Software objects interact and communicate with each other by sending messages to
each other. When object A wants object B to perform one of B’s methods, object A
sends a message to object B
There are three parts of a message: The three parts for the message
System.out.println{‘‘Hello World’’}; are:
• The object to which the message is addressed (System.out)
• The name of the method to perform (println)
• Any parameters needed by the method (“Hello World!”)

Encapsulation

Object diagrams show that an object’s variables make up the center, or nucleus, of
the object. Methods surround and hide the object’s nucleus from other objects in the
program. Packaging an object’s variables within the protective custody of its methods
is called encapsulation.

Encapsulating related variables and methods into a neat software bundle is a
simple yet powerful idea that provides two benefits to software developers:
• Modularity: The source code for an object can be written and maintained independently
of the source code for other objects. Also, an object can be easily
passed around in the system. You can give your bicycle to someone else, and it
will still work.
• Information-hiding: An object has a public interface that other objects can use
to communicate with it. The object can maintain private information and methods
that can be changed at any time without affecting other objects that depend
on it.

Fundamentals of Objects and Classes

We move now from the conceptual picture of objects and classes to a discussion of
software classes and objects.4
Objects are closely related to classes. A class can contain variables and methods.
If an object is also a collection of variables and methods, how do they differ from
classes?

Objects and Classes
Objects
In object-oriented programming we create software objects that model real world objects.
Software objects are modeled after real-world objects in that they too have
state and behavior. A software object maintains its state in one or more variables. A
variable is an item of data named by an identifier. A software object implements its
behavior with methods. A method is a function associated with an object.
Definition: An object is a software bundle of variables and related methods.
An object is also known as an instance. An instance refers to a particular object.
For e.g. Karuna’s bicycle is an instance of a bicycle—It refers to a particular bicycle.
Sandile Zuma is an instance of a Student.
The variables of an object are formally known as instance variables because they
contain the state for a particular object or instance. In a running program, there
may be many instances of an object. For e.g. there may be many Student objects.
Each of these objects will have their own instance variables and each object may have
different values stored in their instance variables. For e.g. each Student object will
have a different number stored in its StudentNumber variable.

Thursday, March 11, 2010

Classes and Instances

The next important principle of object-oriented programming is
All objects are instances of a class. The method invoked by an object in
response to a message is determined by the class of the receiver. All objects
of a given class use the same method in response to similar messages.
Fred is an instance of a category or class of people i.e. Fred is an instance of a
class of florists. The term florist represents a class or category of all florists. Fred is
an object or instance of a class.
We interact with instances of a class but the class determines the behaviour of instances.
We can tell a lot about how Fred will behave by understanding how Florists
behave. We know, for example, that Fred, like all florists can arrange and deliver
flowers.
In the real world there is this distinction between classes and objects. Real-world
objects share two characteristics: They all have state and behavior. For example, dogs
have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail).
Students have state (name, student number, courses they are registered for, gender)
and behavior (take tests, attend courses, write tests, party).

Messages and Responsibilities

Members of an object-oriented community make requests of each other. The next
important principle explains the use of messages to initiate action:
Action is initiated in object-oriented programming by the transmission of a
message to an agent (an object) responsible for the actions. The message
encodes the request for an action and is accompanied by any additional
information (arguments/parameters) needed to carry out the request. The
receiver is the object to whom the message is sent. If the receiver accepts the message, it accepts responsibility to carry out the indicated action. In
response to a message, the receiver will perform some method to satisfy the
request.

There are some important issues to point out here:
• The client sending the request need not know the means by which the request
is carried out. In this we see the principle of information hiding.
• Another principle implicit in message passing is the idea of finding someone else
to do the work i.e. reusing components that may have been written by someone
else.
• The interpretation of the message is determined by the receiver and can vary
with different receivers. For example, if you sent the message “deliver flowers”
to a friend, she will probably have understood what was required and flowers
would still have been delivered but the method she used would have been very
different from that used by the florist.
• In object-oriented programming, behaviour is described in terms of responsibilities.
• Client’s requests for actions only indicates the desired outcome. The receivers
are free to pursue any technique that achieves the desired outcomes.
• Thinking in this way allows greater independence between objects.
• Thus, objects have responsibilities that they are willing to fulfill on request. The
collection of reponsibilities associated with an object is often called a protocol.

Sunday, March 7, 2010

Object Orientation as a New Paradigm: The Big Picture

It is claimed that the problem-solving techniques used in object-oriented programming
more closely models the way humans solve day-to-day problems.3
So lets consider how we solve an everyday problem: Suppose you wanted to send
flowers to a friend named Robin who lives in another city.To solve this problem you
simply walk to your nearest florist run by, lets say, Fred. You tell Fred the kinds of
flowers to send and the address to which they should be delivered. You can be assured
that the flowers will be delivered.
Now, lets examine the mechanisms used to solve your problem.
• You first found an appropriate agent (Fred, in this case) and you passed to this
agent a message containing a request.
• It is the responsibility of Fred to satisfy the request.
• There is some method (an algorithm or set of operations) used by Fred to do
this.
• You do not need to know the particular methods used to satisfy the request—
such information is hidden from view.

Off course, you do not want to know the details, but on investigation you may find
that Fred delivered a slightly different message to another florist in the city where
your friend Robin lives. That florist then passes another message to a subordinate
who makes the floral arrangement.The flowers, along with yet another message, is
passed onto a delivery person and so on. The florists also has interactions with wholesalers
who, in turn, had interactions with flower growers and so on.
This leads to our first conceptual picture of object-oriented programming:
An object-oriented program is structured as community of interacting agents
called objects. Each object has a role to play. Each object provides a service
or performs an action that is used by other members of the community.

Saturday, March 6, 2010

Logic Programming

Prolog (PROgramming in LOGic) 2 is the most widely available language in the logic
programming paradigm. It is based on the mathematical ideas of relations and logical
inference. Prolog is a declarative language meaning that rather than describing
how to compute a solution, a program consists of a data base of facts and logical
relationships (rules) which describe the relationships which hold for the given application.
Rather then running a program to obtain a solution, the user asks a question.
When asked a question, the run time system searches through the data base of facts
and rules to determine (by logical deduction) the answer.
Logic programming was an attempt to make a programming language that enabled
the expression of logic instead of carefully specified instructions on the computer.
In the logic programming language Prolog you supply a database of facts and
rules; you can then perform queries on the database.
This is also an example of a declarative style of programming where we state or
define what we know.
In the following example, we declare facts about some domain. We can then query
these facts—we can ask, for example, are sally and tom siblings?
sibling(X,Y) :− parent(Z,X), parent(Z,Y).
parent(X,Y) :− father(X,Y).
parent(X,Y) :− mother(X,Y).
mother(trude, sally).
father(tom, sally).
father(tom, erica).
father(mike, tom).
The factorial function is written in prolog as two rules. Again, notice the declarative
nature of the program.
fac(0,1).
fac(N,F) :− N > 0,
M is N − 1,
fac(M,Fm),
F is N Fm.
To summarize:

• In procedural languages, everything is a procedure.
• In functional languages, everything is a function.
• In logic programming languages, everything is a logical expression (predicate).
• In object-oriented languages, everything is an object.

Functional programming

Functional programming is a programming paradigm that treats computation as the
evaluation of mathematical functions. Functional programming emphasizes the definition
of functions, in contrast to procedural programming, which emphasizes the
execution of sequential commands.
The following is the factorial function written in a functional language called Lisp:
(defun factorial (n)
(if (<= n 1) 1 ( n (factorial (− n 1))))
)
Notice that it defines the factorial function rather than give the steps to calculate it.
The factorial of n is defined as 1 if n <= 1 else it is n factorial(n − 1)

Programming Paradigms

Object-oriented programming is one of several programming paradigms. Other programming
paradigms include the imperative programming paradigm (as exemplified
by languages such as Pascal or C), the logic programming paradigm (Prolog), and the
functional programming paradigm (exemplified by languages such as ML, Haskell or
Lisp). Logic and functional languages are said to be declarative languages.
We use the word paradigm to mean “any example or model”.
This usage of the word was popularised by the science historian Thomas Kuhn.
He used the term to describe a set of theories, standards and methods that together
represent a way of organising knowledge—a way of viewing the world.
Thus a programming paradigm is a
. . . way of conceptualising what it means to perform computation and how
tasks to be carried out on a computer should be structured and organised.
We can distinguish between two types of programming languages: Imperative
languages and declarative languages. Imperative knowledge describes how-to knowledge
while declarative knowledge is what-is knowledge.
A program is ”declarative” if it describes what something is like, rather than how
to create it. This is a different approach from traditional imperative programming
languages such as Fortran, and C, which require the programmer to specify an algorithm
to be run. In short, imperative programs make the algorithm explicit and
leave the goal implicit, while declarative programs make the goal explicit and leave
the algorithm implicit.
Imperative languages require you to write down a step-by-step recipe specifing
how something is to be done. For example to calculate the factorial function in an
imperative language we would write something like:
public int factorial(int n) {
int ans=1;
for (int i = 2; i <= n; i++){
ans = ans i;
}
return ans;
}
Here, we give a procedure (a set of steps) that when followed will produce the
answer.

What is Object Oriented Programming?

OBJECT-ORIENTATION is a set of tools and methods that enable software engineers
to build reliable, user friendly, maintainable, well documented, reusable software systems that fulfills the requirements of its users. It is claimed that object-orientation
provides software developers with new mind tools to use in solving a wide variety of
problems. Object-orientation provides a new view of computation. A software system
is seen as a community of objects that cooperate with with each other by passing
messages in solving a problem.
An object-oriented programming laguage provides support for the following objectoriented
concepts:
Objects and Classes
Inheritance
Polymophism and Dynamic binding

OBJECT-ORIENTED PROGRAMMING

OBJECT-ORIENTED PROGRAMMING (OOP) represents an attempt to make programs
more closely model the way people think about and deal with the world. In the older
styles of programming, a programmer who is faced with some problem must identify
a computing task that needs to be performed in order to solve the problem. Programming
then consists of finding a sequence of instructions that will accomplish that
task. But at the heart of object-oriented programming, instead of tasks we find objects
– entities that have behaviors, that hold information, and that can interact with
one another. Programming consists of designing a set of objects that model the problem
at hand. Software objects in the program can represent real or abstract entities
in the problem domain. This is supposed to make the design of the program more
natural and hence easier to get right and easier to understand.
An object-oriented programming language such as JAVA includes a number of
features that make it very different from a standard language. In order to make
effective use of those features, you have to “orient” your thinking correctly.