Saturday, 30 May 2015

Java Methods

Java methods are equivalent to C++ functions. Objects can communicate with each other using methods. Java’s methods can be classified in the two categories:


  • Instance Methods
  • Static Methods 


Just like static variables and instance variables, there are static methods and instance methods.

1. Instance Methods

The general form of an instance method is:

<return-type> <method-name> (parameter-list)

{

<method-body>

}

Method definition has four parts:


  • Name
  • Return Type
  • List of Parameters
  • Method Body

The return type can be a primitive data type or reference data type. In case, the method returns a 
reference, the return type will be the name of the class to which the object referred to by the returned reference belongs. It is must to declare the return type even if the method does not return any value. In this case, the return type should be declared as void.

The method’s formal parameters/arguments are specified within the parenthesis after the method name. The syntax is same as in C/C++.

The method body may contain any valid Java statement. If the method has a return type, then a value must be returned through return statement.

Invoking/Calling Instance Methods

The dot (.) operator is used to invoke/call the instance methods. The general form for calling the 

instance methods using the dot operator is: 

<object-reference>.<method-name>(paremeter-list)

Where <object-reference> is some reference variable pointing to an object and <method-  name> is the name of an instance method. For example, after creating an object of type Box and storing its reference in the reference variable b1, we can call the instance method  volume() using dot operator as follows: 

Box b1 = new Box();

b1.volume();

Instance methods can access the instance variables as well as static variables.

Example: The following program demonstrates how to call a instance method.

1 class Box 

2 { double width; //instance variables

3 double height;

4 double depth;

5 void volume() //instance method

6 { System.out.println("volume is:" + width * height * depth); 

7 }

8 }

1 class BoxDemo_4

2 { public static void main(String args[])

3   { Box b = new Box();

4 b.width = 10; 

5 b.height = 20;

6 b.depth = 15;

7 b.volume();

8 }

9 }

In the main() method an instance of the class Box is created, its instance variables are initialized and then the instanced method is called. The instance method volume() calculates and displays the volume of the Box.

While accessing an instance variable inside main() method, we have used object reference. It is required, as we can not access an instance variable directly inside a static method. However, when an instance variable is accessed by a method that is defined in the same class as the instance variable, the instance variable can be referred directly. 

In fact we cannot specify the object reference in the method volume(), in the above example. This is due to the fact that unlike instance variables, there is only one copy of the instance methods. The instance methods use the copy of the instance variables of the object through which they are called. So the same method called through different object references will use different copy of the instance variables and hence the name instance method.

Implicitly an instance variable referred directly in a method uses this reference. For example, in the above program the direct reference to variables width, height and length is equivalent to this.width, this.height and this.length. The reference this inside a method refers to the current object (i.e. the object on which the method is called). The reference this is replaced by the reference of the invoking object at run-time. Hence the same instance method invoked through different objects will use different set of instance variables and hence will normally give different results.

Example: The following program demonstrates that calling non-static/instance method on different objects results in different output. 

1 class Box 

2 { double width; //instance variables

3 double height;

4 double depth;

5 void volume() //instance method

6 { System.out.println("volume is "+width*height*depth); 

7 }

8 }

1 class BoxDemo4

2 { public static void main(String args[])

3   { Box b1 = new Box();

4 Box b2 = new Box();

5 b1.width = 10; b1.height = 20; b1.depth = 15;

6 b2.width = 3; b2.height = 6;  b2.depth = 9;
7 b1.volume();

8 b2.volume();

9   }

10 }

The first call to method volume() displays the volume of the box b1 correctly as 6000 and the 
second call to method volume() displays the volume of the box b2 as 162.

Method Returning a value

Example: The following program demonstrates use of method, which returns a value i.e. its 
return type, is not void.

1 class Box 

2 { double width;

3 double height;

4 double depth;

5 double volume()

6 { return width * height * depth; 

7 }

8 }

1 class BoxDemo5

2 { public static void main(String args[])

3   { Box b1 = new Box();

4 Box b2 = new Box();

5 double vol;

6 b1.width = 10;

7 b1.height = 20;

8 b1.depth = 15;

9

10 b2.width = 3;

11 b2.height = 6;

12 b2.depth = 9;

13 vol = b1.volume();

14 System.out.println("Volume is : " + vol);

15 vol = b2.volume();

16 System.out.println("Volume is : " + vol);

17 }

18 }

Passing Arguments to Methods.

In the previous examples using class BoxDemo5, we initialized the instance variables directly to 
keep the things simple. This should not be done as it defeats the purpose of data encapsulation.

Moreover the instance variables can be made private so that they cannot be accessed from other 
classes. In that case it would not be possible to access the instance variables directly. The only 
alternative in that case is to define a method that takes width, height, and length as arguments 
and then initializes the instance variables.

Example: The following program defines two classes: Box and BoxDemo6. The class Box has a 
method that takes arguments. The classes may be defined in same source file or in two different 
source files. But in both the cases you will get two classes after compilation: Box.class and 

BoxDemo6.class. You can execute only class BoxDemo6.class as only this class has main() 
method. It also makes use of class Box for creating an instance/object and calling methods.

1. class Box

2. { private double width, height, depth; //data hiding

3. double volume()

4. { double vol = width * height * depth;

5. return vol;

6. }

7. void setDimensions(double w, double h, double d)

8. { width = w;

9. height = h;

10. depth = d; 

11. }

12. /* Instance Variable Hiding 

13. void setDimensions(double width,double height,double depth)

14. { width = width;

15. height = height;

16. depth = depth; 

17. }

18. */

19. /* Instance Variable Hiding 

20. void setDimensions(double width,double height,double depth)

21. { this.width = width;

22. this.height = height;

23. this.depth = depth; 

24. }

25. */

26. }

1 class BoxDemo6

2 { public static void main(String args[])

3    { Box b1 = new Box();

4 Box b2 = new Box();

5 b1.setDimensions(10, 20, 30);

6 double volume = b1.volume();

7 System.out.println(volume);

8 b2.setDimensions(5, 10, 15);

9 volume = b2.volume();

10 System.out.println(volume);

11 }

12 }

You cannot access the instance variables of class Box though object reference in the class 
BoxDemo6 as instance variables are declared private. The private instance variables can be 
accessed only in the class in which they are declared.

Nesting of Instance Methods

One instance method can invoke the other instance method of the same class without qualifying 
i.e. by just specifying the method name. For example, in the following program, calCost() 
method, which is an instance method, can call the instance method area() of the same class 
simply by its name.

1 class Circle

2 { static final float  PI = 3.1415f;

3 float puCost; // say cost of painting unit area

4 float radius;

5 float area()

6 { return PI * radius * radius;

7 }

8 float calCost()

9 {

10 float cost = puCost * area();

11 return cost;

12 }

13 public static void main(String args[])

14 { Circle circle = new Circle();

15 circle.puCost = 100;

16 circle.radius = 3;

17 float area = circle.calCost();

18 System.out.println(area); 

19 }

20 }

2. static Methods 

The static methods can be accessed like static variables through the class name without creating 
any instance/object. The static methods can also be called using the object reference. The static 
methods can directly access only static variables irrespective of the fact that they are invoked 
through class name or object reference.

The general form of a static method is:

static <return-type> <method-name> (parameter-list)


<method-body>


The general form is same as that of a instance method with the only difference that the modifier 
static is used before the return type.

Invoking/Calling static Methods

Example: The following program demonstrates the use of static method. The method area() 
takes one argument representing the radius of the circle and calculates its area. The method area() does not use any instance variable so it is declared as static and can be invoked through class name without creating any instance/object.

1 class Circle

2 { static final float  PI = 3.1415f;

3 static float area(float radius)

4 { return PI * radius * radius;

5 }

6 public static void main(String args[])

7 { int r = 4;

8 float area = Circle.area(r); 

9 //float area = area(r); //Nesting of static methods 

10 System.out.println("Area: "+area); 

11 }

12 }

Here the static variable PI is declared to be constant by putting modifier before the type. This is 
equivalent to const of C/C++.

Nesting of Class Methods

One class method can invoke the other class method of the same class without qualifying i.e. by 
just specifying the method name. For example, in the above program main() method, which is 
static can call the static method area() of the same class simply by its name: 

float area = area(r);

This nesting can go to any depth.

Java Variables

Java has three kinds of variables:


  • Local variables
  • Instance variables
  • Static Variables


We have already discussed about local variables. Local variables are used inside blocks or methods. The other two types of variables (also referred to as data members) are defined within the class but outside any method/block.

1. Instance Variables

A class provides the data encapsulation by declaring the variables within the class definition. For example, in the class Box defined above, the variables width, height and length are instance variables. Instance variables are declared in the same way as local variables except that they are declared outside the methods.

An instance variable occupies the memory on the per-object basis. For example, if you create two objects of type Box using operator new then both the objects will have different set of variables corresponding to instance variables width, height and length.

Initialization

The instance variables are initialized as soon as the object is created i.e. as soon as the memory is allocated with the new operator. The variables are initialized according to their types as shown in
the following tables.

For example, as soon as an object of type Box is created, the instance variables width, height and

length are initialized to 0 (Zero).

Accessing Instance Variables

The dot (.) operator is used to access the instance variables. The general form for accessing the
instance variables using the dot operator is:

<Object Reference>.<Variable Name>

Where <Object Reference> is some reference variable pointing to an object and <Variable
Name> is the name of an instance variable. For example, after creating an object of type Box and
storing its reference in the reference variable box, we can access the instance variables using dot
operator as follows:

box.width box.height box.length

Thus the way of accessing instance variables is very similar to the way in which we access the
members of structures in C or C++. But there is one significant difference. In C/C++, we can
access structure members directly as well as through pointers. But in Java program, we never
have access to an object directly. We always access an object through its reference. Thus the dot
(.) operator of Java is like -> operator of C/C++.

We can assign values to instance variables just like local variables as shown below:

box.width = 10; box.height = 20; box.length = 30;

We can use instance variables in expressions as shown below:

double vol =  box.width * box.height * box.length;

We can display the values of the instance variables, just like local variables as shown below:

System.out.println(box.height);

Example: The following program demonstrates the concepts discussed till now.

1 class Box

2 { double width;

3 double height;

4 double depth;

5 public static void main(String args[])

6   { Box b = new Box();

7 double vol;

8 b.width = 10;

9 b.height = 20;

10 b.depth = 15;

11 vol = b.width * b.height * b.depth;

12 System.out.println("volume is " + vol);

13 }

14 }

Example: The following program provides the same functionality as the previous one but it uses
two classes: Box and BoxDemo. Here it is assumed that both the classes are defined in different
files: Box.java and BoxDemo.java. It is also possible to define both the Java classes in one file.

Box.java

1 class Box

2 { double width;

3 double height;

4 double depth;

5 }

BoxDemo.java

1 class BoxDemo

2 { public static void main(String args[])

3    { Box b = new Box();

4 double vol;

5 b.width = 10;

6 b.height = 20;

7 b.depth = 15;

8 vol = b.width * b.height * b.depth;

9 System.out.println("volume is " + vol);

10  }

11 }

Compiling Box.java will generate Box.class file and compiling BoxDemo.java will generate
BoxDemo.class file. After compiling these two files you should run the BoxDemo class, because
it contains the main() method.
It is not necessary for both the Box and BoxDemo classes to be in the different source file. For
example, both the classes might be defined in the source file Box.java but compiling this file will
also generate two different classes: Box.class and BoxDemo.class.

Example: The pervious example is modified so that the classes Box.java and BoxDemo.java
belong to the package p1.

Box.java

1 package p1;

2 class Box

3 { double width;

4 double height;

5 double depth;

6 }

BoxDemo.java

1 package p1;

2 class BoxDemo

3 { public static void main(String args[])

4 { Box b = new Box();

5 double vol;

6 b.width = 10;

7 b.height = 20;

8 b.depth = 15;

9 vol = b.width * b.height * b.depth;

10 System.out.println("volume is " + vol);

11 }

12 }

To run the above program you should put both the classes in folder p1 in the working folder and
then give the following command from the working folder (parent of p1):

java p1.BoxDemo

The folder p1 will be created automatically (if it does not exist), in the working folder, if you
compile the above java files using the command:

javac  -d . Box.java

javac  -d . BoxDemo.java

Example: The pervious example is modified so that the classes Box.java and BoxDemo.java
belong to package p1 and p2 respectively.

Box.java

1 package p1;

2 public class Box

3 { public double width; //instance variables

4 public double height;

5 public double depth;

6 }

BoxDemo.java

1 package p2;

2 import p1.*;

3 class BoxDemo

4 { public static void main(String args[])

5    { Box b = new Box();

6 double vol;

7 b.width = 10; b.height = 20; b.depth = 15;

8 vol = b.width * b.height * b.depth;

9 System.out.println("volume is " + vol);

10   }

11 }

The folder p1 and p2 will be created automatically (if do not exist), in the working folder, if you
compile the above java files using the commands:

javac  -d . Box.java

javac  -d . BoxDemo.java

To run the above program you should give the following command from the working folder

(parent of p1 and p2):

java  p2.BoxDemo

Note that the class Box is declared public as it used in class BoxDemo that belongs to a different
package.  Similarly all the data members of the class Box are also declared public as they are
being accessed in class BoxDemo.

Also note that the class BoxDemo imports class Box so that it can use the class without
qualifying with the package name.

Example: Creating two instances of Box class
If you have two Box objects, each has its own copy of depth, width, and height. It is important to
understand that changes to the instance variables of one object have no effect on the instance
variables of another.

Box.java

1 class Box

2 { double width; //instance variables

3 double height;

4 double depth;

5 }

BoxDemo2.java

1 class BoxDemo2

2 { public static void main(String args[])

3  { Box b1 = new Box();

4 Box b2 = new Box();

5 double vol;

6 b1.width = 10;

7 b1.height = 20;

8 b1.depth = 15;

9 b2.width = 3;

10 b2.height = 6;

11 b2.depth = 9;

12 vol = b1.width * b1.height * b1.depth;

13 System.out.println("volume is " + vol);

14 vol = b2.width * b2.height * b2.depth;

15 System.out.println("volume is " + vol);

16    }

17 }

2. Static Variables

Static variables are also declared outside methods/blocks like instance variables. But the static
variables make use of the modifier static before the data type. For example, the variable width in
the previous example can be made static variable if declared as:

static double width;

The static variables are global to a class and all of its instances (objects). They are useful for
keeping track of global states. For example, a static variable count in a class can store the
number of instances/objects of the class created in the program at any instance of time. The
objects can communicate using static variables just like C functions communicate through global
variables.

For static variables there is only one copy of the variable irrespective of number of instances/objects created in the program, which is shared across all the instances.

The dot (.) operator is used to access the static variables also. The general form for accessing the static variables using the dot operator is:

<Class Name>.<Variable Name>

Where <Class Name> refers to the name of the class in which the static variable is declared and
<Variable Name> is the name of a static variable. For example, if we declare the variables width,
height and depth as static then we can access them using dot operator as follows:

Box.width

Box.height

Box.length

We can also access the static variables through object reference and dot operator as follows but any reference will point to the same copy:

box.width

box.height

box.length

Example: The following example illustrates that for static variables there is only one copy of the
variable irrespective of number of instances/objects created in the program, which is shared across all the instances.

Initialization

The static variables are initialized as soon as the class is loaded/used. The variables are initialized with default values according to their types. The default values are same as those for instance variables.

Box.java

1 class Box

2 { static double width;

3 static double height;

4 static double depth;

5 }

BoxDemo.java

1 class BoxDemo3

2 { public static void main(String args[])

3    { Box b1 = new Box();

4 Box b2 = new Box();

5 double vol;

6 b1.width = 10;

7 b1.height = 20;

8 b1.depth = 15;

9

10 b2.width = 3;

11 b2.height = 6;

12 b2.depth = 9;

13 vol = b1.width * b1.height * b1.depth;

14 System.out.println("volume is " + vol);

15 vol = b2.width * b2.height * b2.depth;

16 System.out.println("volume is " + vol);

17  }

18 }

Java assigning object reference variables

The following example explains what happens when we assign one object reference to another object reference.

Example: 

Box b1 = new Box();

Box b2 = b1;

You might think that b2 is being assigned a reference to a copy of the object referred to by b1. That is, you might think that b1 and b2 refer to separate and distinct objects. However, this would be wrong.

Instead, after this fragment executes, b1 and b2 will both refer to the same object. The assignment of b1 to b2 did not allocate any memory or copy any part of the original object. It simply makes b2 refer to the same object, as does b1. Thus, any changes made to the object through b2 will effect the object to which b1 is referring, since they are the same object.

Although b1 and b2 both refer to the same object, they are not linked in any other way. For example, a subsequent assignment of null to b1 will simply unhook b1 from the original object without affecting the object or b2:

Box b1 = new Box();

Box b2 = b1;

.

b1 =null;

Here, b1 has been set to null, but b2 still points to the original object.

Note: When you assign one object reference variable to another object reference variable, you are not creating a copy of the object, you are only making a copy of the reference.

Java Allocating Memory using Operator new

The memory for Java objects is always allocated dynamically with the help of new operator. For
example, an instance/object of the class Box can be created as follows:

Box box = new Box();

For the sake of understanding we can compare new operator with the malloc() of C. In the above
example, new operator will allocate memory for an object of class Box and return its reference, which is then assigned to reference type variable box. The reference type variable box will now refer to an object of type Box as shown below:

The new Operator


It is important to understand that new allocates memory for an object during runtime. Since memory is finite, it is possible that new may not be able to allocate memory for an object because in-sufficient memory exists. If this happens, a run-time error will occur.

Java Declaring Objects

You can declare object of class Box as follows:

Box box;

Normally we say that box is an object of type Box. This is correct in C++ but this is not fully correct in Java. Because box is simply a variable that can hold reference to an object of type Box.

This is like pointer to a structure in C/C++. The reference box will store garbage or null reference unless we assign reference of some object of class Box to it.

After the above declaration variable box will contain garbage or null reference as shown below:

This indicates that variable box is not pointing to any object.

If the variable box is defined in a method or block it will contain garbage, as local variables are not initialized by default. To make sure that it contains null unless some valid reference (conceptually same as pointer of C/C++) is assigned to it, you must declare and initialize the box as follows:

Box box = null;

If the above declaration of box is outside any method/block then it is an instance variable and there is no need not initialize it with null as an instance/reference variables are always initialized with null.

Java Access/Visibility Modifiers

Access/visibility modifiers control access to a class, interface, data member or method. There are four levels of visibility in Java:


  • public
  • protected
  • package
  • private

1. Access/Visibility Modifiers for Top-Level Classes.

Visibility of a top-level class can be either public or package.

public

The keyword public is the only modifier, which can be used with a top-level class. If a class is to 
be visible to all the classes irrespective of their package, then it must be declared as public by specifying the modifier public, which should appear before the keyword class.

package

There is no keyword package for visibility control. In the absence of any access/visibility modifier before the top-level class, its visibility is only within the package in which it is defined. The concept of package is somewhat similar to the concept of friend classes in C++.

2. Access/Visibility Modifiers for Data Members and Methods.

When used in the variable or method declarations, access/visibility modifiers control access to the variable or method i.e. they decide who can access the variables and methods. These modifiers are not applicable for local variables as their visibility/scope is anyhow limited to the method/block in which they are declared.

public

Any method or variable is always visible in the class in which it is declared. The instance methods of a class can access any other method (instance as well as static method) or variable (instance as well as static variable) declared in the class. Similarly a static method of a class can access any other static method or static variable declared in the same class. 

If a method or variable is to be visible to all the classes, then it must be declared as public by specifying the modifier public, which should appear before the data type. For example, main() method is always declared as public. The reason is that main() method is accessed by the code which is part of JVM i.e. it is outside the class in which main() method is declared. Similarly an instance or static variable can be declared public by specifying modifier public as shown below:

public float width;
public static float width;

A variable or method declared as public has the widest possible visibility. It can be accessed from any class.

private

If you want that a method or variable should not be visible outside the class in which it is declared then its access modifier should be private. We use this modifier to hide the variable or method so that it cannot be accessed from outside the class. 

A variable declared as private has the least possible visibility but it is the most commonly used modifier to encourage data encapsulation and data hiding.  

package 

There is no keyword package. In the absence of any access/visibility modifier before a data member or method, its visibility is only within the package in which it is defined.

protected

A variable declared as protected can be accessed from all the classes belonging to the same package as that of the class in which member is declared. This visibility is similar to the package scope. But in addition to this a protected member can be accessed from any child class irrespective of the package in which it is declared.

Example: A simple class Box is defined below.

1 class Box
2 {
3    double width;
4    double height;
5    double length;
6 }

Example: The class Box is redefined here to include one method volume().

1 class Box
2 {
3    double width;
4    double height;
5    double length;
6    void volume()
7    {
8        double vol = width * height * length;
9        System.out.println(vol);
10  }
11 }

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");

}

}

Java Jump Statements

Jump statements are used for breaking the control flow. Java supports the following jump statements:

  • break
  • labeled break
  • continue
  • labeled continue
  • return
Beside this the constructs used for exception handling can also be put into this category but they are discussed in a separate chapter.

break Statement

The general form of simple break statement is:

break;

The unlabeled break statement can be used inside loops (for, while and do-while) and switch statements. It terminates the containing statement and transfers the control outside the closest enclosing loop or switch statement. The rest of containing statement body is skipped and the execution continues after the containing statement.

This is similar to break statement in C/C++. Refer to examples of simple-if statement and switch statement discussed above for the use of break statement.

labeled break Statement

The syntax of the labeled break statement is as follows:

break  <label>;

The labeled beak statement is used to terminate the block whose label is specified in the break statement. Unlike simple break statement, you can terminate any block. For example, it is possible to terminate the outermost loop from inside a deeply nested for loop.

The break statement can also be used to terminate a simple block (i.e. the block need not be a loop or switch statement)

Example: The following program searches for a given element inside a matrix (2-D array) and makes use of the labeled break statement to come out of the outermost for loop as soon as the element is found.

import java.util.*;

class SearchMatrix

{ 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 : ");

number = in.readLine();

x = Integer.parseInt(number);

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

matrix[i][j]= Integer.parseInt(number);

{

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

{

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

{ found = true;

}

 break outerloop;
}

}
}
if(found)

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

else

System.out.println("The number " + x + " is not present");
}
}

The use of labeled break statement in the above program is a substitute of the labeled goto statement of C/C++. This is a better alternative, as the program is more readable hence the labeled break is referred to as the civilized form of goto statement.

Java Iteration Statements (Loop Control Structure)

The Java supports the while, do-while and for iteration/loop control statements. The syntax is similar to C/C++. With JDK1.5, a second form of for was added that implements a “for-each” style loop.

while Statement

The general form of a while statement is:

while(condition)

loop body

Loop body may contain one or more statements. If loop body contains more than one statement then they must be enclosed between braces.

Example: The following program accepts one natural number say n as command line argument and then calculates and displays the sum of first n natural numbers.

class SumNaturalNumbers

{

public static void main(String a[])

{ int n, sum=0;

n = Integer.parseInt(a[0]); //command line argument

int i = 1;

sum = 0;

while (i <= n)

{

sum = sum + i;

i  = i + 1;

}

System.out.println("Sum of first " + n + " natural numbers is " + sum);

}

}

do-while Statement

The general form of a do-while statement is:

do

{

} while (condition)

loop body

Example: The following program accepts one integer number say n as command line argument and then calculates and displays the sum of its digits.

class SumOfDigits

{ public static void main(String a[])

{ int n, m, sum, digit;

n = Integer.parseInt(a[0]); //command line argument

m = n;

if(m < 0)

m = -m;

sum = 0;

do

{ digit = m % 10;

sum = sum + digit;

m = m / 10;

}while (m > 0);

System.out.println("Sum of digits of number " + n + " is: " + sum);

}

}

for Statement

The general form of a for statement is:

for(initialization; condition; increment/decrement)

loop body

Loop body may contain one or more statements. If loop body contains more than one statement then they must be enclosed between braces.

Example: The following program accepts one natural number say n as command line argument

and then calculates and displays the sum of first n natural numbers.

class SumNaturalNumbers1

{ public static void main(String a[])

{ int i, n, sum;

n = Integer.parseInt(a[0]); //command line argument

for(i = 1, sum = 0; i <= n; i++)

{

sum = sum + i;

}

System.out.println("Sum of first " + n + " natural numbers is " + sum);
}
}