Saturday, 30 May 2015

Java defining a class

A Java class represents a user-defined data type. It acts like a template using which we can create multiple objects. The objects are like variables /instances of the data type represented by the class. To begin with you can think of a class as struct of C with the difference that a struct data type can have only data as members whereas the class can have data as well as methods as its members.

The general form of a class is

modifiers class <classname>
{
      <body of the class>
}

The body of the class can consist of data members as well as methods.
The general form is expanded below to show the fact that the class body can contain data members (variables) as well as methods.

modifiers class <classname>
{
modifiers type variable1;
modifiers type variable2;
.

.

modifiers type methodname1(parameter-list)
{
     <body of the method>
}

modifiers type methodname2(parameter-list)
{
     <body of the method>
}

.

.

}

Friday, 29 May 2015

Basic Concepts of OOP (Object-Oriented Programming)

Some of the essential elements of the object-oriented programming are mentioned below:


  • Abstraction
  • Objects and Classes
  • Three OOP Principle
                   Encapsulation
                   Inheritance
                   Polymorphism

  • Persistence
  • Genericity
  • Composition/Aggregation
1. Abstraction

The abstraction is one of the essential elements of any programming language including the procedural languages. The concept of built-in data type is also an abstraction. The feature of defining own data type using struct in C language further extends this abstraction.

The basic purpose of abstraction is to reduce complexity by hiding details. For example, people do not think of car as a set of hundreds of components. They think of it as a well-defined object having some unique properties and behavior.

Abstraction can be defined as an act for identifying the essential properties and behaviors of an object without going into details. The properties and behaviors of an object differentiate it from other objects of similar type and also help in classifying/grouping the objects.

The object-oriented programming languages model abstractions using classes and objects.

2. Objects and Classes

Object

An object is a physical or abstract entity or thing, which can be distinguished from other objects of similar types. An object has three characteristics:

(i) Identification
(ii) Properties (Attributes)
(iii) Behaviors (Methods/Operations/Functions)

The object can also be thought of as an instance of class, where class is like a built-in data type and object is a variable.

Class

A class represents a category of objects with similar properties and behaviors. A class can be thought of as a blueprint for creating objects. An object has the properties and behaviors defined by its class. The class can be thought of as a user-defined data type and object as a variable/instance of the data type represented by the class.

The properties/attributes of an object are defined by data members/fields in Java. A data member/field in a class is a variable that can hold data. The behaviors/operations of an object are defined using methods in Java. Both data members and methods are referred to as members of the class.

A class may also be thought of as a user-defined data type and an object as a variable of that data type. Once a class has been defined we can create any number of objects belonging to that class.

3. Three OOP Principles

3.1 Encapsulation

Encapsulation is the mechanism that binds code and data on which the code acts. Java classes support this as they allow us to define the code and data together. Encapsulation also helps in achieving data hiding by declaring some of the class members as private so that they cannot be accessed from the code that does not belong to the class.

3.2 Inheritance

In object-oriented programming, inheritance refers to the properties of a class being available to other classes called sub-classes or derived-classes. A sub-class or derived class is one that is derived from an existing class. It inherits all the features of the existing class which is also referred as the base-class or super-class. So inheritance can be defined as the process of deriving a class from a super-class or a base-class. Inheriting a class does not introduce any changes in the base-class/super-class. The derived-class/sub-class has a larger set of properties and behaviors as compared to the base-class.

The major advantage of the inheritance is code reusability. If the base class is in use for a long time and there is a need to add some extra attributes and methods, we can do so by deriving another class. The derived class will be able to use code of the base class without debugging as it is in use for a long time

Class Hierarchy

All the classes derived from a common base class belong to a family and form a class hierarchy. The class hierarchy can be compared with a tree structure where one base class is at the root and does not have a super-class. All other classes are either derived from the class at the root of the hierarchy or from some other class, which is derived from the root class directly or indirectly.

More features are added as we go down the tree. The classes that are represented by the leaf nodes do not have any sub-classes. The following examples show some class hierarchies.

Example 1: You can derive classes Saving Account and Current Account from the class Account. Here Account is the Base/Super Class and Saving Account and Current Account are Derived/Sub classes.

Example 2: The following diagram shows the classes derived from the Base class Vehicle.

3.3 Polymorphism

Polymorphism is a feature that allows same interface to be used for a general class of actions.

Most of the object-oriented languages use polymorphism in the following situations:

  • Operator Overloading
  • Method Overloading
  • Method Overriding

Operator Overloading

Most of the languages use this form of polymorphism for the built-in operations. For example, all the arithmetic operators in C/C++ or Java can be used with many types of operands (int, long, float, double etc.). So same addition operator can be used to add two integers as well as to add

two floating-point numbers. 

The C++ allows the user to overload the built-in operators. For example, you can overload the 

arithmetic operators to handle the complex numbers also. Although Java uses operator 

overloading for built-in operators but does not allow the user to overload the operators.

Method Overloading

This feature allows us to write more than one methods with the same name. Both C++ and Java have this feature. The methods (functions in C++) with same name are differentiated based on the parameters. The overloaded methods must either have different number of parameters or the types of the parameters must differ if their number is same.

If the call to an overloaded method can be resolved at compile time i.e. if the compiler can decide which of the overloaded method will be called then this is called static binding, which is an example of compile time polymorphism. 

If the call to an overloaded method cannot be resolved at compile time i.e. if the compiler cannot 
decide which of the overloaded method will be called then this is called dynamic binding, which 
is an example of run-time polymorphism. 

In general Java resolves calls to overloaded methods at run-time but there are many situations 
where the calls to overloaded methods are resolved at compile-time.

Method Overriding

The sub-class can define a method with the same name as in the super-class, and same number and type of parameters. This is called method overriding. 

The compiler can not resolve call to an overridden method. Java normally uses dynamic binding to resolve calls to overridden methods i.e. the decision takes place at run-time.

4. Persistence

Some object-oriented languages allow you to store/retrieve the state of a program to/from a persistent storage media i.e. a permanent storage media like secondary storage. This is called persistence.

Java allows you to store any object on the secondary storage and to retrieve it later on. If you attempt to store an object at the top of an object graph, all of the other referenced objects are recursively located and saved. Similarly when the object is retrieved later on, all of the objects and their references i.e. the entire object graph is correctly created in the main memory.

For example, it is possible to save an entire tree structure by just saving the root of the tree. At a
later stage it is possible to recreate the entire tree structure in the memory by just retrieving the root.
The C++ does not support this feature.

5. Genericity

The concept of defining an algorithm once, independently of any specific type of data, and then 
applying that algorithm to a wide variety of data types without any additional effort is called Genericity. 

C++ supports this feature using templates. Java also supports this feature through Object class, 
which is at the top of any class hierarchy in Java.

For example, using this feature, we can implement a generic data type stack so that it is possible 
to store element of any type in the stack.

This feature increases the degree of reusability to a large extent.

6. Composition/Aggregation

An object might be made up of other objects. Such an object is called Composite or Aggregate 
object. For example, it is appropriate if an object of class vehicle is defined as a composite object 
made up of objects like Engine, Body, Axle, Seats etc.

Inheritance v/s Composition

There are two basic mechanisms for deriving new classes from the existing ones: Inheritance and 
Composition. 

The class Bus can be derived by inheriting properties of class vehicle. Here Bus is a kind of vehicle which has some additional properties / behaviors beside the properties and behaviors which are common for all the vehicles. In other words class Bus has is-a relationship with the class vehicle as we can say that Bus is a vehicle.

The class vehicle itself might be derived from many other classes using composition. For example, an object of class vehicle might be composed of objects belonging to classes like Engine, Gear Box, Seats, Driver’s Seat, Body, Steering Wheel etc. The derived class in this case has whole-part relationship with the classes representing parts of the composite object. We can not say that Vehicle is an Engine or Vehicle is a Gear Box as Vehicle is made up of a number of parts.

Object-Oriented Programming v/s Procedural Programming

All the programs consist of two elements: process and data.  There can be two different approaches depending upon whether our main focus is on processing or data. The procedural programming languages (C, FORTRAN, PASCAL, COBOL etc.) focus on the processing part i.e. they give more importance to “what is happening” in the system and less importance to data.

The object-oriented languages (Java, C++) focus on the data i.e. they give more importance to “who is being affected”. The procedural approach becomes less and less suitable as the programs become large and complex. The object-oriented programming languages were developed to overcome the limitations of the procedural programming languages. The object-oriented programs are relatively far less complex as compared to the similar programs written in procedural languages.

Object-oriented programs are organized around data (i.e. objects) and a set of well-defined
interfaces (public methods) to that data. Java is based on object-oriented paradigm. Java is almost pure object-oriented programming language. We have used the term “almost” as Java also supports Primitive Data Types due to performance reasons. The C++ is not a pure object-oriented language. C++ is an extension to C so it uses an approach, which is a mix of procedure-oriented approach and object-oriented approach.

The basic differences in the two approaches are summarized below:

(i) The object-oriented programs are data centric while the programs written in procedural
languages are process centric.

(ii) The object-oriented programs are organized around data (objects) so they model the real
world objects in a better way.

(iii) The degree of reusability and extensibility of code is very high in case of object-
oriented approach as compared to procedural approach. So code size is less.

(iv) The object-oriented programs are easier to maintain, as they are relatively less complex
and smaller in size.

(v) The object-oriented programs are based on the bottom-up design methodology while
the procedural programs are based on the top-down design methodology.

Java return Statement

The return statement is used to immediately return control from a called method to the calling method.

The syntax of the return statement is as follows:

return;

or

return expression;

The first form of return statement is used to simply transfer control from the called method to the calling method. The second form returns control as well as returns a value to the calling method as specified by the expression following the return statement.

Java continue Statement

The general form of simple continue statement is:

continue;

The unlabeled continue statement can be used inside loops (for, while and do-while) only. It prematurely stops the current iteration of the loop body and proceeds with the next iteration, if possible.

In the case of while and do-while loops, the rest of the body is skipped and the execution continues with the loop condition. In the case of for loop, the rest of the body is skipped and the execution continues with the increment/decrement expression.

This is similar to continue statement in C/C++.

Example: The linear search program is rewritten to make use of the continue statement.

import java.util.*;

class LinearSearch

{ public static void main(String args[]) throws IOException

{ int n, x, a[]; boolean found = false; String number;

Buffered Reader in

= new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter the number of elements in the array: ");

number = in.readLine(); n = Integer.parseInt(number);

a = new int[n];

for(int i = 0; i < n; i++)// read the array elements

{ number = in.readLine();

a[i] = Integer.parseInt(number);

}

System.out.print("Enter the element to be searched in the array: ");

number = in.readLine(); x = Integer.parseInt(number);

int i = 0;

while(i < n && !found) // search the specified element

{

if(x = =  a[i]) // simple if statement

{

found = true;

continue;

}

i++;

}

if(found) // if-else statement

System.out.println("The number " + x + " is present in the list");

else

System.out.println("The number " + x + " is not in the list");
}
}

labeled continue Statement

The syntax of the labeled continue statement is as follows:

continue  <label>;

The labeled continue statement specifies the label of the enclosing loop to continue. The label need not correspond to the closest enclosing loop.

Example: The matrix search program is rewritten here to make use of the continue statement.

import java.util.*;

class SearchMatrix1

{ public static void main(String args[]) throws IOException

{

int i, j, x, row, col , matrix[][];  String number;  boolean found = false;

Buffered Reader in = new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter the number of rows in the matrix: ");

number = in.readLine(); row = Integer.parseInt(number);

System.out.print("Enter the number of columns in the matrix: ");

number = in.readLine(); col = Integer.parseInt(number);

matrix = new int[row][col];

for(i = 0; i < row; i++) //enter one element in one line

{

System.out.println("enter the elements of row " + (i+1));

for(j = 0; j < col; j++)

{ number = in.readLine();

}

}

System.out.print("Enter the element to be searched in the matrix: ");

number = in.readLine();

x = Integer.parseInt(number);

outerloop: for(i = 0; i < row && !found; i++)

{ for(j = 0; j < col; j++)

{ if(matrix[i][j] == x)

{ found = true;

continue outerloop;

}

}

}

// break will transfer control to the following statement

if(found)

System.out.println("The number "+ x + " is present in the matrix");

else

System.out.println("The number " + x + " is not in the matrix");

}

}