Object - Oriented Programming - Java
Object - Oriented Programming - Java
A BRIEF HISTORY OF OBJECT- ORIENTED PROGRAMMING 1.1 The need for an efficient programming paradigm.
The development of complex software systems such web applications, operating systems, network software, and a vast array of application software available today would likely be impossible if humans were forced to write programs in machine language. Dealing with the intricate detail associated with such languages while trying to organize complex systems would be a taxing experience. Consequently, programming languages have been developed with paradigms that allow algorithms to be expressed in a form that is both palatable to humans and easily convertible to machine language instructions. These languages allow humans to avoid the intricacies of registers, memory addresses, and machine cycles during the program development process, so that they can concentrate on the properties of the problems being solved. Programming paradigms have evolved over the years in the software development industry, the most recent and efficient of them being the object-oriented programming paradigm.
Computer hardware can understand instructions only in the form of machine codes i.e. 0's and 1's. A programming language used to communicate with the hardware of a computer is known as low-level language or machine language. It is very difficult for humans to understand machine language programs because the instructions contain a sequence of 0s and 1s only. Also, it is difficult to identify errors in machine language programs. Moreover, low-level languages are machine dependent. To overcome the difficulties of machine languages, high-level languages such as Basic, Fortran, Pascal, COBOL and C were developed. High-level languages allow some English-like words and mathematical expressions that facilitate better understanding of the logic involved in a program. While solving problems using high-level languages, importance was given to develop an algorithm (step by step instructions to solve a problem). While solving complex problems, a lot of difficulties were faced in the algorithmic approach. Hence object-oriented programming languages such as C++ and Java were evolved with a different approach to solve the problems. Object-oriented languages are also highlevel languages with concepts of classes and objects. An object-oriented programming language such as JAVA includes a number of features that make it very different and more efficient than a standard language.
CHAPTER
INTRODUCTION TO OBJECT- ORIENTED PROGRAMMING 2.1 The need for object oriented programming.
In todays competitive world, the need of the hour is to develop simple and speedy solutions that can be instantly applied to varied requirements. This has resulted in the creation of different complex software systems. However, although the complexity of a software system is a reality, there are ways to ensure that this complexity does not become a stumbling block to the smooth functioning of the software. One way of simplifying this complexity is to split the software system into its component parts and arrange the parts in a hierarchy. This is similar to the way in which the employees of an organization can be grouped according to the functions they perform and they are arranged in a hierarchy. Before Object Oriented Programming (OOP) came into effect, procedural programming was in use. Programs written by using the procedural programming approach consist of various functions. These functions can be executed anywhere within the program. A function in a program contains the instructional steps that are performed to carry out an activity. The functions of a procedural program are interdependent and, therefore, difficult to separate from one another. These interdependent functions cannot be reused in other programs. As a result, even for a similar task across programs, the entire function has to be recoded. This made program development a complex task For example, you have a program, EmployeeDetails, coded in procedural language that keeps the details of employees of a bank. The program has a function, printDetails that prints the details of each bank employee. This function can be called many times from different parts of the same program. If you want to print the details of a different organization, by using the same function, printDetails, then you have to recode it in another program. In addition, data in procedural programming is visible and accessible throughout the program, making it easy to manipulate the data from anywhere in the program. Some examples of procedural languages are COBOL, PASCAL and BASIC. All procedural languages lack support for OOP.
3
The limitations of procedural programming led to the evolution of the object oriented approach. In OOP the program is broken into independent chunks known as objects, which can be integrated to create a complete program. For example, in OOP you can have an Employee object that keeps the details of employees of any organisation. The same Employee object can have functions to print these employee details. Any program can reuse this Employee object. Thus objects can be reused across various programs. This enables a programmer to develop an application in a relatively shorter duration. OOP enables to consider a real world entity as an object. OOP combines userdefined data and instructions into a single entity called an object. In OOP, objects can be placed in libraries. OOP also offers some built in libraries. These libraries consist of a set of objects and are predefined functions. They can be reused by all programs. A major advantage of OOP is the reusability of code because it saves the effort required to rewrite the same code for every program using the functions defined in libraries.
A procedure or a subprogram is a set of commands that can be executed independently. In a program following procedural methodology, each step of a subprogram is linked to the previous step. For example in a program that needs to accept, display and print data, you can divide the program into subprograms. You can create three subprograms that accept data, display data, and print data respectively. Each program performs a defined function while the combined action of subprograms makes a complete program.
Variable A Variable B Variable C Procedure 1 (Accept Data) Accept value of A Accept value of B
Program
Procedure 2 (Display Data) Display Value of A Display Value of B C=A+B Procedure 3 (Print Data) Print Value of A Print Value of B Print Value of C
Fig 2.1 Procedural Programming. The preceding figure displays a program that consists of three procedures, Accept Data, Display Data, and Print Data. Data is accepted in the Accept Data procedure, displayed in the Display Data procedure, and printed in the Print Data procedure. Procedural programming is used for developing simple applications. Some benefits of procedural programming methodology include: o Easy to read program code o Easy maintainable program code as various procedures can be debugged in isolation. o Code is more flexible as you change a specific procedure that gets implemented across the program. The features of procedural programming methodology are: o Large programs are divided into smaller programs. o Most of the data is shared as global that can be accessed from anywhere within the program. In procedural programming approach, portions of the code are so interdependent that the code in one application cannot be reused in another.
5
For example, the module used to calculate the salary of the employees in a bank management system cannot be used to calculate the salary of employees in an educational institute. The disadvantages of procedural programming approach include: o When you need to reuse the procedural program in another application, a change in the application results in rewriting a large portion of the code. This results in decreased productivity. o The maintenance cost of the application is considerably increased. These are some of the reasons that led to the evolution of the object oriented approach.
Benefits of object-oriented programming include: o Reduced cognitive load (have less to think about and more natural paradigm). o Isolation of programmers (better team programming). o Less propagation of errors. o More adaptable/flexible programs. o Faster development due to reuse of code.
CHAPTER
3.1 Abstraction.
Real world objects are very complex and it is very difficult to capture the complete details. Hence, OOP uses the concepts of abstraction and encapsulation. Abstraction is a design technique that focuses on the essential attributes and behavior. It is a named collection of essential attributes and behavior relevant to programming a given entity for a specific problem domain, relative to the perspective of the user. Closely related to encapsulation, data abstraction provides the ability to create user-defined data types. Data abstraction is the process of abstracting common features from objects and procedures, and creating a single interface to complete multiple tasks. For example, a programmer may note that a function that prints a document exists in many classes, and may abstract that function, creating a separate class that handles any kind of printing. Data abstraction also allows user-defined data types that, while having the properties of builtin data types, it also allows a set of permissible operators that may not be available in the initial data type. In Java, the class construct is used for creating user-defined data types, called Abstract Data Types (ADTs). An abstraction should define a related set of attributes and behavior to satisfy the requirement. Knowing the ISBN number of a book is irrelevant for a reader whereas for a librarian, it is very important for classification. Hence, the abstraction must be relevant to the given application. Separation of interface and implementation is an abstraction mechanism in object-oriented programming language. Separation is useful in simplifying a complex system. It refers to distinguishing between a goal and a plan. It can be stated as separating what is to be done from how it is to be done. The separation may be well understood by the following equivalent terms:
What
How
3.2 Encapsulation.
From the users point of view, a number of features are packaged in a capsule to form an entity or object. This entity offers a number of services in the form of interfaces by hiding the implementation details. The term encapsulation is used to describe the hiding of the implementation details. The advantages of encapsulation are: o information hiding o implementation independence If the implementation details are not known to the user, it is called information hiding. Restriction of external access to features results in data hiding. The driver may not know the steering mechanism, but knows how to use it. Here, the hidden steering mechanism refers to information hiding. Whatever type of steering is used, the way of using the steering is same. Rotating the steering wheel is an example of interface. The steering wheel is visible to the driver (user) and its function is not affected by the change in the implementation by a different type of steering mechanism such as power steering. The users interface is not affected by changing the implementation mechanism. A change in the implementation is done easily without affecting the interface. This leads to implementation independence. Thus, the natural way of solving a problem involves abstraction and encapsulation. The process, or mechanism, by which you combine code and the data it manipulates into a single unit, is commonly referred to as encapsulation. Encapsulation is a process of hiding non-essential details of an object. It allows an object to supply only the requested information to another object and hides non-essential information. Since it packages data and methods of an object, an implicit protection from external tampering prevails. However, an entire application cannot be hidden. A part of the application needs to be accessed by users to use an application. Abstraction is used to provide access to a specific part of an application. It provides access to a specific part of data while encapsulation hides data.
10
Abstraction
Abstraction separates interface and implementation. User knows only the interfaces of the object and how to use them according to abstraction. Thus, it provides access to a specific part of data. Abstraction gives the coherent picture of what the user wants to know. The degree of relatedness of an encapsulated unit is defined as cohesion. High cohesion is achieved by means of good abstraction.
Encapsulation
Encapsulation groups related concepts into one item. Encapsulation hides data and the user cannot access the same directly (data hiding).
Coupling means dependency. Good systems have low coupling. Encapsulation results in lesser dependencies of one object on other objects in a system that has low coupling. Low coupling may be achieved by designing a good encapsulation. Encapsulation packages data and functionality and hides the implementation details (information hiding). Encapsulation is a concept embedded in abstraction.
Abstraction is defined as a data type called class which separates interface from implementation.
The ability to encapsulate and isolate design from execution information is known as abstraction.
3.3 Inheritance.
Inheritance allows the extension and reuse of existing code, without having to repeat or rewrite the code from scratch. Inheritance involves the creation of new classes, also called derived classes, from existing classes (base classes). Allowing the creation of new classes enables the existence of a hierarchy of classes that simulates the class and subclass concept of the real world. The new derived class inherits the members of the base class and also adds its own. For example, a banking system would expect to have customers, of which we keep information such as name, address, etc. A subclass of customer could be customers who are students, where not only we keep their name and address, but we also track the educational institution they are
11
enrolled in. Inheritance is mostly useful for two programming strategies: extension and specialization. Extension uses inheritance to develop new classes from existing ones by adding new features. Specialization makes use of inheritance to refine the behavior of a general class. When a class is derived through inheriting one or more base classes, it is being supported by multiple inheritance. Instances of classes using multiple inheritance have instance variables for each of the inherited base classes. Java does not support multiple inheritance. However, Java allows any class implements multiple interfaces which provides similar feature to multiple inheritance.
3.4 Polymorphism.
Polymorphism allows an object to be processed differently by data types and/or data classes. More precisely, it is the ability for different objects to respond to the same message in different ways. It allows a single name or operator to be associated with different operations, depending on the type of data it is passed, and gives the ability to redefine a method within a derived class. For example, given the student and business subclasses of customer in a banking system, a programmer would be able to define different getInterestRate() methods in student and business to override the default interest getInterestRate() that is held in the customer class.
12
CHAPTER
INTRODUCTION TO JAVA
Java is an object oriented programming language that was designed to meet the need for a platform independent language. Java is used to create applications that can run on a single computer as well as a distributed network. Java is both a language and a technology used to develop standalone and Internet based applications. With the increasing use of the internet, Java has become a widely used programming language.
o Platform-independence is a programs capability of moving easily from one computer system to another. At the source level, Javas primitive data types have consistent sizes across all development platforms. Javas foundation class libraries make it easy to write code that can be moved from platform to platform without the need to rewrite it to work with that platform. Platform-independence doesnt stop at the source level, however. Java binary files are also platform-independent and can run on multiple problems without the need to recompile the source. Java binary files are actually in a form called bytecodes. o Bytecodes are a set of instructions that looks a lot like some machine codes, but that is not specific to any one processor. Normally, when you compile a program written in C or in most other languages, the compiler translates your program into machine codes or processor instructions. Those instructions are specific to the processor your computer is runningso, for example, if you compile your code on a Pentium system, the resulting program will run only on other Pentium systems. If you want to use the same program on another system, you have to go back to your original source, get a compiler for that system, and recompile your code. Figure 4.1 shows the result of this system: multiple executable programs for multiple systems. Things are different when you write code in Java. The Java development environment has two parts: a Java compiler and a Java interpreter. The Java compiler takes your Java program and instead of generating machine codes from your source files, it generates bytecodes.
Compiler (Pentium)
To run a Java program, you run a program called a bytecode interpreter, which in turn executes your Java program (see Figure 4.2). You can either run the interpreter by itself, or for applets, there is a bytecode interpreter built into HotJava and other Java-capable browsers that runs the applet for you.
Compiler (Pentium)
small also makes it more robust because there are fewer chances for programmers to make difficult-to-find mistakes. Despite its size and simple design, however, Java still has a great deal of power and flexibility. Java is modeled after C and C++, and much of the syntax and object-oriented structure is borrowed from the latter. Although Java looks similar to C and C++, most of the more complex parts of those languages have been excluded from Java, making the language simpler without sacrificing much of its power. There are no pointers in Java, nor is there pointer arithmetic. Strings and arrays are real objects in Java. Memory management is automatic. To an experienced programmer, these omissions may be difficult to get used to, but to beginners or programmers who have worked in other languages, they make the Java language far easier to learn.
16
use classes and objects for representing the concepts of abstraction and encapsulation. The software structure that supports data abstraction is known as class. A class is a data type capturing the essence of an abstraction. It is characterized by a number of features. The class is a prototype or blue print or model that defines different features. A feature may be a data or an operation. Data are represented by instance variables or data variables in a class. The operations are also known as behaviors or methods or functions. They are represented by member functions of a class in C++ and methods in Java and C#. A class is a data type and hence it cannot be directly manipulated. It describes a set of objects. For example, apple is a fruit implies that apple is an example of fruit. The term fruit is a type of food and apple is an instance of fruit. Likewise, a class is a type of data (data type) and object is an instance of class. Similarly car represents a class (a model of vehicle) and there are a number of instances of car. Each instance of car is an object and the class car does not physically mean a car. An object is also known as class variable because it is created by the class data type. Actually, each object in an object-oriented system corresponds to a real world thing, which may be a person or a product or an entity. The difference between class and object are given in Table 4.1.
Class
Class is a data type. It generates object. It is the prototype or model. Does not occupy memory location. It cannot be manipulated because it is not available in the memory.
Object
Object is an instance of class data type. It gives life to a class. It is a container for storing its features. It occupies memory location. It can be manipulated.
17
CHAPTER
width
18
We want two instance variables called length and width. Both will be integer numbers. An integer is a positive or negative whole number. Here we define two instance variables of type int. We give the name of the type and then the name of the instance variable. class Rectangle { private int length; private int width; <list of methods> }
19
class Rectangle { private int length; private int width; public int calculateArea() { return length * width; } public int calculatePerimeter() { return (2 * length) + (2 * width); } } We also need a method to initialize the length and width instance variables of each new object that we create. Methods that initialize new objects are called constructors. The name of the method is the same as the name of the class. The syntax of a Java constructor declaration is as follows: public <class name> (<parameters>) { <list of local variables> <statement 1>; <statement 2>; ... <statement n>; } In our constructor we need to initialize length and width. Our constructor needs to have two parameters giving these values. These two parameters are also of type int. Storing a value into a variable is called assignment. public Rectangle (int l, int w) { length = l; width = w; } /* width = w means store (assign) the value of w into variable width */ /* Program 1.1: a class whose instances represent rectangles */ class Rectangle { private int length; // used to store the length of the rectangle private int width; // used to store the width of the rectangle
20
/* declare a constructor to initialise new instances of class Rectangle */ public Rectangle(int l, int w) { length = l; // store the value of l into length width = w; // store the value of w into width } /* declare a method to calculate the area of a rectangle */ public int calculateArea() { return length * width; } /* declare a method to calculate the perimeter of a rectangle */ public int calculatePerimeter() { return (2 * length) + (2 * width); } }
representing our rectangle, area to store its area, perimeter to store the length of its perimeter. class RectangleProgram {
public static void main (String args[]) { Rectangle shape; int area; int perimeter; <statement 1>; <statement 2>; ... <statement n>; } } /*shape is of type Rectangle*/ /*area and perimeter are of type int*/
To create a new 15 X 30 Rectangle object we say: shape = new Rectangle (15,30) ; /*new creates a new object. A reference to the new object is stored in shape. We use the Rectangle constructor to initialize the length and width*/ To calculate the area of our Rectangle object we say: area = shape.calculateArea () ; /*shape is the object on which we are invoking a method. The area of the object is stored in the local variable area. calculateArea is the method that we are invoking.*/ To calculate the perimeter of our Rectangle object we say: perimeter = shape.calculatePerimeter(); /*shape is still the object on which we are invoking the method. The length of the perimeter is stored in the local variable perimeter. calculatePerimeter is the method that we are invoking*/ System class is used to read from and write to the console System class methods are used to read/write to the console -no instance is created. Use the print and println methods to write out the area/perimeter. To write out the area/perimeter we write: System.out.print(The area of the rectangle is: ); System.out.println(area);
22
Our written Java application thus becomes: class Rectangle { private int length; private int width; public Rectangle(int l, int w) { length = l; width = w; } public int calculateArea() { return length * width; } public int calculatePerimeter() { return (2 * length) + (2 * width); } } class RectangleProgram {
public static void main (String args[]) { Rectangle shape; int area; int perimeter; shape = new Rectangle (15,30) ; area = shape.calculateArea () ; perimeter = shape.calculatePerimeter(); System.out.print (The area of the rectangle is: ); System.out.println(area); System.out.print (The perimeter of the rectangle is: ); System.out.println (perimeter); } } This written program prints to the screen: The area of the rectangle is : 450 The perimeter of the rectangle is : 90
23
SUMMARY
Computers are used to solve problems. Different styles of programming have evolved in the history of generation of languages. But the problem of reuse and maintenance was not solved by those early languages and this led to the phenomenon called software crisis. To overcome the limitations, software engineering principles were applied and the object oriented paradigm model was found to be suitable for addressing, modeling, and solving complex problems. The diffusion of this paradigm is the result of a continuous shift of programming abstractions from the solution domain to the problem domain. From machine language to the Object-oriented model and beyond; this constant movement has made the activity of finding a solution easier, more understandable, and maintainable. Object-oriented programming uses object models and it resembles the natural way of solving a problem. The concepts of abstraction and encapsulation are used in Object-oriented programming (OOP). The features of OOP are discussed to realize the importance of OOP approach. Examples of OOP languages, advantages, and applications of OOP are presented to know the importance of OOP. Java is an OOP language. The peculiarity of the language being platform independent, secure, and widely distributed makes it a very interesting and important language for solutions in the rapidly developing software engineering industry. Java software works everywhere, from the smallest devices, such as our cellphones, microwave ovens and remote controls to supercomputers. Java programs are independent of the type of computer, telephone, television, or operating system these devices run on. Java applications are efficient and reliable. The success of the banking ATM software is rooted in its source being the Java technology.
24
REFRENCES
o Object Oriented Programming using Java. Notes for the Computer Science Module. School of Computer Science, University of KwaZulu-Natal.
o Basic Object Oriented Programming, Matty Hall, Larry Brown. (http:// www.corewebprogramming.com)
o Learning to Program the Object-Oriented Way with Java. First program 2000 V. Cahill
o Understanding Object-Oriented Programming with JAVA. Timothy Budd Oregon State University.
o Object Oriented Programming with Java: Essentials and Applications. Rajkumar Buyya, The University of Melbourne and Manjrasoft Pvt Ltd, Australia. Thamarai Selvi Somasundaram, Anna University Chennai, India. Xingchen Chu, The University of Melbourne, Australia
o An Introduction to Scientific and Technical Computing with Java. Clark S. Lindsey, Jonny S. Tolliver and Thomas Lindblad.
o Great Ideas in Computer Science with Java. Alan W. Biermann and Dietolf Ramm.
25