Search This Blog

Showing posts with label Object Oriented Programming. Show all posts
Showing posts with label Object Oriented Programming. Show all posts
Sunday, 16 October 2011

Basic Building Blocks of C++

0 comments
INTRODUCTION TO C++
C++ is an Object Oriented Programming language. Initially named “C with classes”, C++ was developed by Bjarne Stroustrup at AT & T Bell laboratories in Murray Hill, New Jersey, U.S.A., in the year 1980. C++ is an extension of C with a major addition of ‘class’ construct – a feature of Simula67 language.
Since the class was a major addition to the original C language, Stroustrup called the new language ‘C with classes.” However, later in 1983, the name was changed to C++. The idea of C++ comes from the C increment operator ++, thereby suggesting that C++ is an augmented (incremented) version of C.
C++ language corrects most of the deficiencies of C by offering improved compile-time type checking and support for modular and object-oriented programming. The ultimate goal of C++ is to provide a language for the professional programmer that can be used to develop OOP software without sacrificing Cs efficiency or portability.
C++ is a superset of C. Most of what we already know about C applies to C++ also. Therefore, all C programs are also C++ programs. The Object Oriented features in C++ allows programmers to build large programs with clarity, extensibility and easy of maintenance.
Fundamental elements of C++:
Character sets are the basic building blocks of any programming language. In C++, the character set consists of upper and lower case alphabets, digits, special characters and white spaces. The alphabets and digits constitute the alphanumeric set.
The smallest individual units in a program are known as tokens. Tokens are formed using one or more characters from the character set. C++ has the following tokens:
  • Keywords
  • Identifiers
  • Constants
  • Operators
  • Terminals
A C++ program is written using one or more tokens, white spaces, and the syntax of the language. As mentioned earlier, C++ is a superset of C and therefore most constructs of C are legal in C++, with their meaning unchanged.
Keywords:
Keywords are special words, which are predefined in a language for a specific purpose in a program. They are explicitly reserved identifiers that can’t be used as names for the program variables or other user-defined programming elements. Some of the keywords which are newly introduced in C++ are as follows:


Keywords
Purpose
int, float, double, char
Primitive data types
class, new, delete
Object creation / deletion
private, public, protected
Scope specifiers in a class
friend, inline, virtual
Qualifier for member functions
throw, try, catch
Exception handling keywords
for, do, while, switch
Control structure keywords

Table : List of Keywords and their purposes
Identifiers:
Identifiers are names given by the user for the programming elements such as variables, symbolic constants, functions, arrays and classes. Each language has its own rules for naming these identifiers. The following points must be noted while forming an identifier in C++:
  1. Identifiers are formed using alphabets, digits and underscore characters.
  2. Every identifier must begin with an alphabet or underscore character.
  3. The maximum number of characters used for forming an identifier must not exceed 31.
  4. Since C++ is a case-sensitive language, same name with different cases are not equal. For instance, names such as rate, Rate, and RATE are treated as different identifiers.
It is a general practice to use lower and mixed case letters for identifiers. But keywords are always in lowercase letters.
Constants:
Constants are values that never change during the execution of a program. For instance, the value 10 is an integer constant, ‘A’ is a character constant and “C++ Programming” is a string constant. When such constants are named using identifiers, they become Symbolic Constants.
Symbolic constants are named constants that can be referred later in a program using the symbol used for their definition. There are two ways of creating symbolic constants in C++:
  1. Using the qualifier const.
  2. Defining a set of integer constants using the keyword enum.
Any value declared as const can’t be modified by the program in any way. Consider the following constant declaration in C++:
const int size = 10;
char name[size];
The above lines of code declare a symbolic constant size with value 10, which is referred in the second line for array declaration using the name size. The default data type for constants is integer (int). For e.g.,
const size = 10;
means
const int size = 10;
The named constants are just like variables except that their values can’t be changed.
Another method of naming integer constant is as follows:
enum{x, y, z);
This defines x, y and z as integer constants with values 0, 1 and 2 respectively. This is equivalent to:
const x = 0;
const y = 1;
const z = 2;
We can also assign values to x, y and z explicitily:
enum {x=100, y=200, z=300}
Such values can be any integer vales.
Continue reading →
Saturday, 15 October 2011

Object Oriented Programming Concepts

0 comments
Object Oriented Concepts
An object is an entity in a real-world problem. It may represent a person, a place, a bank account, a table of data or any other item in the real world. In software scenario, an object refers to a piece of software containing data and code that can be reused.

Video Presentation on Object Oriented Programming Concepts
An object in a running program takes up space in memory and has an associated address to refer to it. Examples for objects used in a banking application are: “customer” and “account.” During execution, objects interact with each other by sending messages and receiving responses.
Class & Object:
Class is a user-defined data type, which defines the structure of an object. Objects are variables or instances of type class. A class defines the type and scope of all its members.
There are two elements defined in a class. They are variables and functions. Variables declared in a class are called data members, and the functions defined in a class are known as member functions.
Every class describes possibly infinite set of individual objects; each object is said to be an instance of its class and each instance has its own value for each attribute. Following are the various definitions of ‘class’ data type:
  1. A class is a template that unites data and operations.
  2. A class is an abstraction of real world entities having similar properties.
  3. A class identifies a set of similar objects.
Defining a member function:
A member function is a function, which is declared and defined for a class. Generally, member functions are declared within the class and defined outside the class. The function definition consists of two sections: a header and a body. The header part defines the signature of the function. It includes return type, name of the function and a set of parameters (variables used for passing information) with their type defined.
The function body contains the code that implements the function. This part can be written either inside or outside the class. To define the function outside the class, use the class name and the scope resolution operator (::) as a prefix to the function name.
Three types of scope specifiers are available for defining the scope of the members in a class. They are: private, protected and public. The scope specifier defines the availability of a member to the outside world. When not specified, the default scope of the members is private.
The private members are available only within the class. Normally, the data members that are hidden from outside access are declared as private variables. But, the member functions are declared under public scope, because they are free to access from other parts of the program. As member functions are the only way to access the private data and functions provided in an object, they are known as ‘interfaces’ to the object.
Encapsulation & Data Hiding:
The wrapping up of data and functions into a single unit (called class) is known as encapsulation. Though a class contains both data and functions, only the functions are available to the public, but not the data. The encapsulated data within the class are not accessible from outside world directly.
The hidden data can be accessed only through the member functions, which act as interfaces between the data and the external program. By declaring variables as private members, we can hide the data of an object. Variables declared as protected also implement data hiding. Such an act of hiding the data from public access is also referred to as data abstraction.
Abstraction of Function definition:
Abstraction refers to the act of representing essential features without exposing the background details required for implementing them. Like data, functions are also abstracted form the user by not showing the details of implementation.
Abstraction of function definition is done by hiding the details like logic and statements used for implementing the services provided by the object. In order to avail the services exposed by an object, the user has to know only the way of accessing the function and not the procedure used to implement it.
Polymorphism:
Polymorphism means having one name but different forms. Polymorphism allows two member functions of a same class to have the same name, but different parameters or return type. There are two types of polymorphism: Compile-time polymorphism and Run-time polymorphism.
Function overloading is an example for compile-time polymorphism. Two functions are said to be overloaded when they have the same name but different number/type of parameters or return type. Because the selection of an overloaded function is determined at compile time by the compiler depending on the parameter passed during function call.
Run-time polymorphism occurs during the function call of an over-ridden function. When a function of a base class (a class used for defining another class) is redefined in its derived class (class newly created from an existing one), it can have the same name, the same set of parameters and the return type as that of the base class function, but different body. In such a case, the selection of the function (function of the base class or the derived class) to be executed will be determined at run-time by the compiler.
Inheritance:
If we want to model an object whose functionality is basically similar to that of another object, then the new object can derive its basic functionalities from an already existing object. For example, the object ‘plastic chair’ inherits all the basic qualities like arms, legs and seat from an idol chair in addition to the extra qualification “material used” for making it.
Inheritance is a concept of OOP that defines the mechanism for creating a new class from an existing class called base class. The base class can be added on or altered to create the new class called derived class. In this way, a hierarchy of related classes can be created and reused in an object oriented programming.
Continue reading →

Merits of OO Methodology

0 comments
Merits of OO Methodology
Object-oriented design involves identification and implementation of different classes of objects and their behavior in a real world problem. The objects in a software system closely correspond and relate to the objects in the real world in a one-to-one manner. Thus, it is easier to design and implement a system consisting of objects.
OOP languages provide a programmer the ability to create modular and reusable code using which formulating a new program can be done easily by composition and modification of some existing modules. The co-operation among different objects is achieved through exchange of messages.
Merits:
Since the objects are autonomous entities and share their responsibilities only by executing methods relevant to the received messages, each object lends itself to greater modularity. Flexibility is also gained by being able to change or replace modules without disturbing other parts of the code. Moreover, the independence of each object eases development and maintenance of the program. The following are some of the merits of Object Oriented methodology:
  1. Information hiding and data abstraction increase reliability and help decouple the procedural and representational specification from its implementation.
  2. Dynamic binding increases flexibility by permitting the addition of new classes of objects without having to modify the existing code.
  3. Inheritance coupled with dynamic binding enhances the reusability of code, thus increasing the productivity of a programmer.
  4. Many OO languages provide a standard class library that can be extended (extend ability) by the users, thus saving a lot of coding and debugging effort.
  5. The advantages of object orientation also includes: shorter development time, high degree of code sharing and malleability (can be molded to any shape).
Demerits:
The runtime cost of dynamic binding mechanism is the major disadvantage of object-oriented languages. The following were the demerits of adopting object-orientation in software development in the early days of computing (some remain forever):
  • Compile time and Run time overhead
  • Re-orientation of software developer to object-orientated thinking
  • Requires the master over the following areas:
    • Software Engineering
    • Programming Methodologies
  • Benefits only in long run while managing large software projects, at least moderately large ones.
Continue reading →
Thursday, 13 October 2011

Object Oriented Methodology

0 comments
Object Oriented Methodology

OO languages combine both data and functions, the core elements of a program into a single entity called object. Objects allow localization of data and code and restrict other objects from referring to their local region.
OOP treats data as the critical element in a program and does not allow the data to flow freely around the system. It ties the data more closely to the functions that operate on them and protects them from accidental modifications from other parts of the program.
The protected data can be freely accessed only from the functions that are associated with them. However, the functions of one object can access the functions of another object. The following are some of the striking features of OOP:
  1. Emphasis is on data rather than procedure.
  2. Programs are divided into what are known as objects.
  3. Date and functions that operate on data are tied together into an entity called object.
  4. Data are hidden within the object and can’t be directly accessed by external functions.
  5. New data and functions can be easily added whenever necessary and
  6. Follows bottom-up approach in program design.
The organization of data and functions in object-oriented programs is shown in the following figure:

Fig. : Organization of data and functions in OOP


Consider an object - account with three attributes: AccountNumber, AccountType, Name and Balance, and three operations: Deposit, Withdraw, and Enquire. The pictorial notation of this object is shown in the below figure:

Fig. : Different styles of representing the object - Account
In C++, objects are coded using a programming element called class. The following code illustrates this:
class account {
private:
char Name[20];
char AccountType;
long int AccountName;
float Balance;
public:
void Deposit();
void Withdraw();
void Enquire();
}
In this example, class is a keyword which indicates the beginning of a new class. The word account is the name of the class. The body of the class containing details about the data and functions of the account object and is enclosed with in a pair of curly braces.
The main advantage of using OO approach is reusability. Through this mechanism, an object already written can be reused to minimize the time and effort required to rewrite similar kind of objects. When a new object requires similar set of functionalities of an existing object and some additional features, instead of designing it from scratch, we can derive (create) it from an existing one.
Continue reading →
Sunday, 9 October 2011

Structured Vs. Object Oriented Programming

0 comments
Software development is a process of creating new software or modifying existing software that will meet the current requirements of its users.  This process consists of various stages or phases in it.  They are:
  1. Problem Definition (Analysis)
  2. Program Design
  3. Coding / Implementation
  4. Testing and
  5. Maintenance
A complete set of all these activities involved in developing software is known as Software Development Life Cycle (SDLC).  This is because the same sequence of steps are to be followed whenever we develop new software from scratch or modifying existing software for up gradation.

Some small programs like text editor (e.g., Notepad) can be coded directly without following all the steps involved in SDLC.  But, large programs like MS Word or MS Excel involve complexity in areas like understanding the problem domain, meeting the customer needs and delivering a good quality product in time.

To overcome the complexities involved in software development, many methodologies, tools and languages were introduced.  Following are two major methodologies introduced for simplifying software development process:
  1. Structured (Procedural) Programming
  2. Object Oriented Programming (OOP)
Structured Programming:
In structured programming model, software designers tend to use Top-Down approach, in which the overall objective of the system is defined first.  Then the system is divided into various sub tasks or sub modules.  With this methodology, software development is done by writing a set of sub programs, called functions that can be integrated together to form a complex system.

In Structured programming, the primary focus is on functions.  A function is a sub program that performs a specific task using the values given to it through input variables (called parameters) and then returns the result to its calling program.  Each function consists of a set of program statements and some local variables.  

A typical program structure for structured approach is shown below:


Fig. : Typical structure of Structure (Procedure) Oriented programs

A function when invoked behaves as though its code is inserted at the point of its call.  The communication between the caller (calling function) and the callee (called function) takes place through parameters.

At the time of function call, the control is transferred from the caller to the first statement of the callee.  All the statements in the function body are executed and then the control is transferred back to the caller to resume the execution of other statements.

Some characteristics exhibited by Structured or Procedural-oriented approach are:
  1. Emphasis is on doing things (algorithms)
  2. Large programs are divided into smaller programs called functions.
  3. Most of the functions share global data.
  4. Data move openly around the system from function to function and
  5. Employs Top-down approach in program design
Limitations of Structured Programming:

Structured programming was a powerful tool that enabled programmers to write moderately complex programs fairly easily.  However, as the programs grew larger, this approach failed to show the desired results in terms of bug-free, easy-to-maintain and reusability of programs.

In this approach, very little attention is given to data used by the function.  And, in a multi-function program, many important data items are placed in the global scope, so that they may be accessed by all functions.  But, this leads to the problem of accidental modification of data due to its access from various functions of the program.  Hence, in a large program it is difficult to keep track of the data items having global scope.

The following picture depicts the relationship of data and function in structured (or) procedural programming:


Fig. :  Relationship of data and functions in Structured programming

Another series drawback with the procedural approach is that it does not model the real world entities to the elements in a program in a one-to-one manner.  This is because the functions are action-oriented and they do not really correspond to the elements of the problem.

Object Oriented Programming:

Object Oriented Programming is centered on new concepts such as objects, classes, polymorphism, and inheritance.  OOP is defined as follows:  It is a method of programming in which programs are organized as co-operative collections of objects, each of which represents an instance of some class and whose classes are all members of a hierarchy of classes united through the property called inheritance.

In this approach, any real world entity can be modeled as an object.  The whole software is considered as a group of objects that work together to accomplish a particular task.  During execution, objects interact with each other by sending messages and receiving responses.

For instance, in a program that performs withdrawal from an account, a customer object may send a withdraw message to a bank account object in order to perform a withdrawal operation.  Any object that communicates with another object need not be aware of its internal workings but only its function signatures.
Continue reading →
Tuesday, 4 October 2011

Creating and Using Packages in Java

0 comments
PACKAGES & INTERFACES!
Packages are nothing but containers like folders that hold one or more classes. A package defines a name space for a set of classes that are related to each other. The name space defined by a package ensures that there are no two classes with the same name. But two packages can have a class with the same name without any name collision among them.
Java uses file system directory to store classes belonging to particular package. For example, the package MyPack will have all its class files in a directory named MyPack. Packages can be nested in a hierarchy i.e., a package can have another package under it.
Classes available in a package can be accessed freely from within the folder that contains it. To make use of them from outside the package, import the package into a Java program using an Import statement. More than one java program can import a package. The following are the steps involved in creating and storing a package:
  1. Include a package command as the first statement in the java file containing class definitions belong to the package.
  2. Create a folder for the package with the same name that of the package (MyPack).
  3. Compile the java files containing classes to get the corresponding class files.
  4. Move the class files from the current folder to the folder having the same name of the package (MyPack).
Defining a Package:
To define a package in a program, simply include a package command as the first statement in a Java source file. Any classes declared after the package command will belong to the specified package.
The package command defines a name space for the classes that are defined after it. The general form of the package statement is:
package pkg;
here, pkg is the name of the package.
An example for a package statement is:
package MyPack;
The following is a C++ program that defines a package named MyPack with two classes: BankAc and BankClient:
package MyPack;
class BankAc{
string name;
double bal;
BankAc(String n, double b)
{
name = n;
bal = b;
}
void Show()
{
System.out.print(“Balance of”);
System.out.println(name + “is” + bal);
}
}
class BankClient{
public static void main(String args[])
{
BankAc sb[] = new BankAc[3];
sb[0] = new BankAc(“Ravi”, 5000.50);
sb[1] = new BankAc(“Raju”, 6000.75);
sb[2] = new BankAc(“Ravi”, 7000.90);


for(int i=0; i<3; i++)
sb[i].Show();
}
}
In this example, two classes are defined for the package MyPack. One is BankAc class that contains two instance variables and two methods for creating and managing a bank account. The second class is an application class named BankClient. After compilation, we will get two class files with the extension .class for the above said classes. These two classes must be stored under the folder created newly with the name MyPack.
Using a Package:
To make use of the classes available in a package from outside the package do the following:
    1. Import the package (MyPack) from a Java program using an import statement containing the package name and
    2. Use the package name and a .(dot) as prefix to the class name that belongs to a Package. For e.g., the BankAc class of MyPack package can be imported as follows:
import MyPack.BankAc;
Nesting a Package:
Nesting a package means having one package defined and stored within another package. Then the package nested becomes a sub package of the main package. To nest a package, specify the name of the parent package(s) and then the sub package, each separated by dot.
The general form of a multilevel statement is shown here:
package pkg1 [pkg2 [pkg3]];
For example, the statement
package java.awt.image;
will create a package with its files stored under the directory
java/awt/image.
Hence, before creating such a package, we should have a directory with the same name and in the same hierarchy as specified in the package statement. Likewise, packages can’t be renamed without renaming the directory in which the classes are stored.
Where to look for Packages?
Importing a package from a Java file will make the run-time system of Java search for the folder containing package. This search starts from the current folder. If it is not found in the current folder, then the path set for Java classes using the command CLASSPATH will be used for searching the package.
Classes stored in a package can be executed from outside the package using the syntax:

java package.classname

For example,
java MyPack.BankAppn
will execute the java class BankAppn.class stored in the package MyPack.
Packages protect Classes:
Packages act as containers for classes and other packages. Classes contain both data and methods (code). Inside the class, we have access specifiers like private and public to have access permission on data and functions at various levels.
The packages, which are at the top level of hierarchy adds another dimension to control the direct access to the classes and its members. Inside a package, a class can be declared with public or private scope. The default scope used for class declaration is private. Only public classes can be accessed for inheritance or object creation from outside the package.


Continue reading →