Sunday, July 29, 2012

How Interfaces are used internally in Java

Before reading this post, I recommend you to go through the following posts:
Interfaces in Java
Runtime Polymorphism in Java
Abstract Classes in Java : Runtime polymorphism

The interfaces have played a key role in making the architecture of Java robust and uniform. The interfaces are used in many places in Java. They are extensively used in JDBC architecture, Collections framework, Multi-threading etc., We will see in detail how interfaces have become crucial for Java to become robust and maintain the uniformity.

Interfaces used in JDBC:

Interfaces are so well used in architecture of JDBC by Java. I should say Java has got most of the flexibility mainly from interfaces and abstract classes. In fact, what Java has done is defined all the method-names in the interfaces. It did not give any implementation for any of the methods. So, what the  DBMS has to do is just use these method-names and build implementation according to the DBMS implementation. In case of migration from one DBMS to other DBMS literally, only the database driver URL, username, password for connection have to be changed.

Now consider a situation without interfaces in Java. In such cases, each DBMS will have its own set of method-implementations and method-names for specific functionalities in Java. Eventually, the method-names for database processing such as executing SQL stored procedures will differ from one DBMS to other DBMS. Now if we want to just change the DBMS we need to change the entire database processing code instead of just changing the driver URL, username and password.


Interfaces used in Multi-Threading:

Similarly interfaces are critical in view of the multi-threading. We know that a thread can be created by two methods.
1. Extending Thread class.
2. Implementing Runnable interface.

Now the first method can impair you in one way. If you extend Thread class, there is no way that you can extend another class since multiple inheritance is not allowed in Java. Now the second option is always good since we can create a class that implements any number of interfaces.

Interfaces used in Collections framework:

Another place where Java has made use of the interfaces is the Collections framework. The Collection framework is the most basic interface. It contains methods to add, remove, search and iterate over list. These are most general functionalities provided. The List, Set and Queue interfaces extend the Collections interface. These interfaces have their specific functionalities in addition to those provided by the Collection interface.

Related Posts:
Interfaces in Java
Runtime Polymorphism in Java
Abstract Classes in Java : Runtime polymorphism
Java Database Connectivity with MS Access -- Part 1
Java Database Connectivity with MS Access -- Part 2
Java Database Connectivity with MS Access -- Part 3

Saturday, July 28, 2012

Interfaces in Java

Before reading this post, I recommend you to read the following posts.
Runtime polymorphism in Java
Abstract Classes in Java:Runtime polymorphism

An interface is a collection of methods that must be implemented by the implementing class. An interface only tells the class what to do. Thus, the interfaces only have the declaration of member variables and methods. Implementing class defines all the methods declared in the interface. If a class implements an interface and does not implement all the methods then the class must be declared as abstract. Variables in interface automatically become static and final variables of the implementing class. Members of interface are implicitly public. A class cannot narrow the accessibility of an interface.

An object reference of an interface can refer to an object of implementing class. However, only methods that are present in the interface can be called using the object reference of interface.

Now lets put the interface into implementation. We consider the implementation of the Stack data structure. Below is the Stack interface and its implementing class MyStack.


The public class which uses the interface and its implementing class is as follows.




Interface Vs. Abstract Class:
Both interface and abstract class cannot have objects, but can have object references. In case of interface, object reference can reference an object of the implementing class. An object reference of abstract class can reference an object of subclass. However, abstract class can have non-abstract methods and instance variables but interface can have neither of them.

Java allows interfaces to be empty. An empty interface contains no variables and methods. It is used to mark a class to be having certain behavior.

Related Posts:
Abstract Classes in Java:Runtime polymorphism
Runtime polymorphism in Java
How Interfaces are used internally in Java

Sunday, July 22, 2012

Abstract Classes: Runtime Polymorphism



Before reading this post, I recommend you to go through Runtime Polymorphism since this post is an extension of the same.

Consider an organization where an Employee can be a Regular Employee or a Consultant. After all, an employee cannot be just an employee. An employee is under one of these categories. To simulate these types of cases in OOP, we make use of abstract classes in Java.

An abstract method (pure virtual function in C++) doesn’t contain a body. An abstract method must be overridden in subclass. Otherwise, the subclass will become abstract.

A class having one or more abstract functions can be declared as an abstract class. We cannot create an object for an abstract class. However, an object reference for an abstract class can be created. Now you may doubt the use of creating a class without an object. For example, in the above example, an object of the Employee class should not be created since an employee cannot just be an employee. Such types of classes should be defined as abstract classes. Now if we allow the objects to be created for an Employee class, it might lead to extra memory usage and also might defeat the very purpose of runtime polymorphism. But we can create an object reference of Employee and point it to an object of its subclass. This is where runtimepolymorphism again comes into picture. In the previous post, you must have already read the golden rule of Runtime Polymorphism: “An object reference of a super class can always point to an object of a subclass.” Instead of the super class object reference pointing to an object of subclass, we now make the abstract class object reference pointing to an object of a subclass.

The implementation for Employee Class is given below.


The implementation for RegularEmployee class is given below.



The implementation for Consultant class is given below.



You can observe that the abstract method in the superclass is overridden in both the above subclasses. Now we will see how runtime polymorphism can be applied using abstract classes.



A class can be declared as an abstract class even though it doesn’t contain any abstract methods. This can be used in situations where there are no abstract functions to be overridden in the subclasses, but at the same time, the abstract class should not have an object.

An abstract class can contain other non-abstract members such as methods and instance variables.

Related Posts:

Sunday, July 8, 2012

Essence of OOP: Runtime Polymorphism in Java

This post does not give the definitions of Runtime polymorphism or Dynamic method dispatch. Instead, it helps Java beginners (or any OOP Beginner) to use runtime polymorphism. I personally think Inheritance and Runtime polymorphism forms the crust of OOP (not just in Java but in all other OOP Languages also).

The entire dynamic method dispatch is based on the rule that an object reference of the super class can refer to an object of any subclass in the hierarchy. This can be explained with the following example.

Consider there are two classes Person and Faculty. Person class is the super class of Faculty class.

Since superclass and subclass share IS A relationship, every Faculty is a Person. So, whenever Java expects Person, a Faculty can be used. This kind of implicit casting is called upcasting.



Unlike in upcasting, every Person need not be a Faculty. Thus, if we use Person in place of Faculty, explicit casting needs to be done. Therefore, we need to use explicit typecasting in order to perform this operation. This kind of explicit casting is called as downcasting.



In runtime polymorphism, the call to an overridden method is resolved at runtime instead of compile time. It occurs when an overridden method is called using an object reference of superclass. Remember that you can only call methods which are present in the super class.

Now let us extend the previous mentioned example with another subclass to "Person" class: NonTeaching class. Now the class diagram is as follows:

The below class demonstrates the runtime polymorphism for the above class diagram.



As can be seen from the code above, Java calls appropriate method depending on the object pointed to by the object reference. In the first case, the object reference p is pointed to the object of Faculty class. So, the printDetails() from the Faculty class is called. In the second case, p points to object of NonTeaching class. Thus, the printDetails() from the NonTeaching class is called.

Always remember that the dynamic method dispatch is applied only to method that is defined in the super class, overridden in subclass and invoked using an object reference of superclass.

Saturday, July 7, 2012

gdb tutorial

Sometimes when you build a project in C++, it might become necessary that the code needs to be changed/added. In such cases, debugging the entire project becomes really very important because you need to ensure that the program flow is correct and no regression takes place.

In this post, we will debug the case study which we implemented in C++ demonstrating the employee register with the help of vectors. To know about how this case study is implemented, read the following posts:
1. Vector Operations - API
2. Vector Operations - Implementation
3. Vector Operations - Implementation part 2

We will use GNU C debugger in order to debug the case study. To start debugging of the case study, first we need to type the following command:

g++ -g "files.cpp"

which in our case transforms to be:

g++ -g EmployeeRegister.cpp Employee.cpp Display.cpp main.cpp

To start debugging, invoke gdb with the following command:

gdb a.out

To debug the entire case study, we will set a breakpoint in main.cpp from the beginning of main function. If you need to debug only a part of a huge project, you can specify that particular file with line number. The idea of this breakpoint is to run the project till that particular breakpoint and from there on, we can inspect or evaluate what each programming statement is actually doing.

break file.cpp:line_no

which in our case is:

break main.cpp:3

Now we want to start running the code line by line with the following command.

run

To go to the next line for debugging, execute the n command in gdb prompt. When you encounter any function and you want to get inside the function definition, use the s command. This is similar to the Step Into functionality in debugging.

In between when you want to check the value of any variable, use the following command:

p variable_name

To exit the GNU C debugger, use the q or quit command.

Now let us use all the above mentioned gdb commands in the case study.



Related Posts:

Vector Operations - API
Vector Operations - Implementation
Vector Operations - Implementation part 2


Sunday, July 1, 2012

Using Eclipse Database Tools -- Access Database from Eclipse IDE


Know Java?? Used Eclipse?? Bored with Database command interface?? Want to access database from Eclipse?? Then this post is for you...
We can access database from the Eclipse IDE itself whenever you want to check some database tables in the middle of a Java or PHP project. So, life becomes easier when you can do everything related to a project in a single tool.

To configure Database access in Eclipse IDE, first we need to open the Database Development perspective. In the Data Source Explorer, you can add a database connection by right-clicking on Database Connection > New.


The list of all the DBMS will be listed in the next wizard as shown below.


Click on the new Driver definition button as indicated in the below figure.


Specify the Driver type > JAR file > Username, Password and Other Database Server details.




You can Test the connection by clicking on the Test Connection Button available in the below wizard. If ping gets succeeded, then click on Next.

Verify whether all the details are correctly filled in and click on Finish.
 

You can see that the new connection added is listed in the Data Source Emplorer view.

The database development perspective in general has Data Source Emplorer, SQL Results, Execution Plan and Bookmarks Views.

The Schemas, Users and Roles on a connected database management system can be viewed in the same Data Source Explorer view.

The SQL Scrapbook can be used to type in SQL commands in Eclipse. You can execute a command by right-clicking on it and selecting the relevant Execute option. Also you can get suggestions as you type in a SQL command in the SQL scrapbook provided by Eclipse.
You can also use SQL Query Builder which is very similar to that of the SQL Scrapbook.

Saturday, June 30, 2012

Vector Operations in C++ -- Part 3

In the last post, we implemented the searching procedure followed in the Employee Register. Now we will discuss the CRUD operations on the vector with Employee class.

To go to the previous two posts,
Vector Operations in C++ -- Part 1 and
Vector Operations in C++ -- Part 2

For adding an employee, we need to first check if another employee of the same employee ID exists in the vector. If it exists, we should give the relevant message to the user. Since we know that adding or deleting the employees at the ends is done very quickly, we have used the function "push_back" to add the new employee to the end.



For displaying the employee details, we must first check if the vector is empty. If it is empty, we need not traverse through the vector.



For deleting and updating an employee details, we need to check if the employee with the given ID exists. If it does not exist, the relevant message must be displayed.



Till now we have done all the operations required for manipulating or displaying the employee data. But a good user interface which is easily understandable by the user is equally important. Thus, we will have a menu with all the above discussed operations. To take numerical and string input from the user, we use two member functions in the class "EmployeeDisplay". Validation to the complete extent is not done for numerical and string inputs.

Compiling and running the case study:

Compiling:
g++ -o EmployeeRegister main.cpp Display.cpp Employee.cpp EmployeeRegister.cpp
Running the executable:
./EmployeeRegister

Sample Output for an add operation in the following menu is given below.



I have uploaded the entire project at the following link: Vector Operations Case Study. You can download the "Employee Register.zip" from this link.

Vector Operations in C++ -- Part 2

Have some information about vectors and want to implement the vector operations?? You have come to the correct place.
In the last post, we have discussed about the operations in vectors and the functions that can be used in vectors. If you do not know about vectors in C++, then refer this page. In this post, we will see the practical implementation of vectors by using a case study.

We are building an employee register in which an employee has two attributes -- a unique Employee ID and the Employee Name. If you want more attributes such as Date of Birth, Work experience, Designations etc., you can add them. But I thought of keeping it simple. So, I have included only two attributes for an employee. I am not linking this case study to any database programming. But I am sure this case study would be very useful in many of the applications based on CRUD and can be used in applications which include database programming. The following actions are done in this case study:
  1. Add a new employee
  2. Display the existing employees
  3. Delete an employee details
  4. Update an employee details
We will have a total of three classes:
  1. Employee class  -- To define the basic attributes of Employee
  2. EmployeeRegister class  -- To do the vector operations on Employee class
  3. EmployeeDisplay class --  Created for User Interface programming

To ensure data abstraction, the header files are separated from the actual implementation. In the header files, the declarations of the variables, classes and methods will be present, while the implementation is covered in the corresponding CPP source files.

First let us see what Employee class has. The following piece of code is Employee.h which declares the variables and the member functions of Employee class.



The implementation of the Employee class are given below. The getters and setters are defined so as to access the member variables in the Employee class.



The implementation of EmployeeRegister class has the following operations:
  1. Adding, Deleting and Updating an employee.
  2. Displaying the current employee details.
  3. Searching for an element in the vector.
  4. Checking whether the vector for Employee class is empty.
We can check if the vector is empty by using the boolean function "empty()" used in vector STL.



Searching is an important operation and will be used by almost all other functions. Imagine you have large number of employee records and you need to search for a record which is the last in the vector. By using linear search, the search process will consume more time. For binary search to be implemented, we need to have the elements in the vector in an increasing order which is not the case here. They can be any possible order. Thus, due to all these factors, the STL algorithm "find" is used to find the position of an element in the vector. For this function to be used, we need to create another vector of integers "emp_id_records". This vector should have all the employee ID's exactly in the same order as that of the emp_records. So, if we can get the position of an element in one vector, we can the index of the other too. 



Friday, June 29, 2012

Vector Operations in C++ -- Part 1

At the end of this series of posts, you will understand the working of vectors, the functions used in vectors. In addition to this, you will be able to do the basic CRUD operations on the vectors.

Vector is a type of sequence container in C++ and is implemented like a dynamic array. Vectors are very similar to arrays except that the arrays have a constant size while vectors can be extended or contracted as needed. However, the size of vector can also be fixed and resized. Once the storage of a vector is exhausted, it grows automatically in size. The storage space they have been allocated can be either equal or greater than the actual size. The extra amount of storage allocated is not used, but is reserved for the vector to be used in case it grows. Thus, the vector does not have to re-allocate storage on each occasion it grows or a new element is inserted.

Similar to arrays, we can access a given element in a vector easily with the index. The elements of vectors are stored in contiguous memory locations just like in the case of arrays. We can iterate over a vector by using its index or by using iterators used in vectors.

Adding or removing the elements from the vector at the ends is done very well as far as the time complexity is concerned. However, the performance of insertion/deletion at positions other than the ends is worse than that of the other sequence containers in C++ (deques and lists).

Constructors for the vector class are as follows:


Constructor Name Syntax Example Description
Default Constructor vector<T> vector_name; vector<int> a; Creates a vector with no elements
Repetitive sequence Constructor vector<T> vector_name(No. of Elements to be repeated, Value to be assigned); vector<int> b(4,100); Creates a vector of 4 elements with value 100.
Iterator constructor vector<T> vector_name (Beginning of another vector, End of another vector); vector<int> c (a.begin(),a.end()); Creates a vector with elements from vector “a”. Can also create a vector by copying only a part of the vector “a”.
Copy constructor vector<T> vector_name(another_vector); vector<int> d(c); Creates a vector by copying the vector “c” into vector “d”.


Accessing an element in a vector:
An element in a Vector can be accessed in two ways:
1. vector_name[index]     (or)
2. vector_name.at(index)

Iterating over a vector using an iterator:
We can iterate over a vector using a normal for loop with the initialization variable from 0 to the vector's maximum size (vector.size( )). But here is another method to explore all the elements in a vector:

vector<int> vector_name;
vector::iterator it;
for(it=vector_name.begin();it < vector_name.end(); it++)
      cout<<*it;

This piece of code will print all the elements one by one in the vector. Similar to iterator, there is also reverse iterator, which iterates over the vector from right to left.

Functions in Vector:

Function Syntax Description
push_back vector.push_back(element) Inserts the element at the end of the vector
pop_back vector.pop_back() Deletes the last element in the vector and returns the same
erase vector.erase(position) Deletes the element from the vector in the specified position/index
insert vector.insert(element,position) Inserts an element (1st argument) into the position (2nd argument)

In the next post, we will apply this concept of vectors in our case study, which involves the basic CRUD operations.
Related Posts Plugin for WordPress, Blogger...