Object- Oriented Programming - Java

Published on June 2017 | Categories: Documents | Downloads: 37 | Comments: 0 | Views: 476
of 25
Download PDF   Embed   Report

Comments

Content

CHAPTER

1

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.

1.2 What object-oriented programming represents.
OBJECT-ORIENTED PROGRAMMING (OOP) represents an attempt to make programs more closely model the way people think about and deal with the world. In the older styles of programming, a programmer who is faced with some problem must identify a computing task that needs to be performed in order to solve the problem. Programming then consists of finding a sequence of instructions that will accomplish that task. But at the heart of objectoriented programming, instead of tasks we find objects (entities that have behaviours), that hold information, and that can interact with one another. Programming consists of designing a set of objects that model the problem at hand. Software objects in the program can represent real or abstract entities in the problem domain. This is supposed to make the design of the program more natural and hence easier to get right and easier to understand.

1

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 0’s and 1’s 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.

2

CHAPTER

2

INTRODUCTION TO OBJECT- ORIENTED PROGRAMMING 2.1 The need for object oriented programming.
In today’s 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.

2.2 Procedural Programming; a closer look.
Procedural programming was born many years ago but it is still popular. Many very popular programming languages like C, Visual Basic and Pascal are procedural programming languages. Many of them are popular because they are easy to learn and are easy way to come into the programming world. Pascal and Visual Basic are representing this part of programming world. First of all it is not true that you can program something only in object oriented languages or that there is something that is only possible to do in procedural programming languages. There is none problem that cannot be solved in both object oriented and procedural languages. Example: Linux kernel is very complex collection of programmes and services and it’s done in c (procedural) and microsoft office is done in Visual C++. So even complex programs can be done in procedural languages. Procedural languages are in many cases easier to learn. Procedural languages are good as starting point and are maybe better for some smaller project but it is not a rule some small programs can be easily done also in object oriented. The procedural programming methodology involves dividing a large program into a set of sub-procedures or sub-programs that perform specific tasks. In this methodology a program is divided into one or more units or modules. These modules can de user defined or can be taken from libraries. A module can consist of single or multiple procedures. These procedures are also known as functions, routines, subroutines, or methods in various programming languages.

4

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.

2.3 The Object Oriented Approach to Programming.
The object oriented programming is a newest methodology in programming. In short words it has classes in which you can incorporate a lot of functions and variables that are common for some part. They can have parents and children and by that share some of its properties. Object oriented programming is much more complicated than procedural programming. But it has many good attributes: code is much more synoptic, that means that it is easy to have many people working on the code without getting confused, it’s easier to change some part of the code without screwing anything. There is also one very important point in object oriented programming and that is software reuse. Classes are included in modules and modules can be added to new programs you write. So if you really want to be a serious programmer you need to learn some object oriented approach to programming. A large application consists of component objects, which interact with each other. These components can be used to develop various applications. This is referred to as the object oriented approach to develop an application. An object is an encapsulated completely-specified data aggregate containing attributes and behavior. Data hiding protects the implementation from interference by other objects and defines approved interface. An objectoriented program is a growing and shrinking collection of objects that interact via messages. You can send the same message to similar objects - the target decides how to implement or respond to a message at run-time. Objects with same characteristics are called instances of a class. Classes are organized into a tree or hierarchy. Two objects are similar if they have the same ancestor somewhere in the class hierarchy. You can define new objects as they differ from existing objects.
6

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.

2.4 Applications of Object Oriented Programming.
Object oriented programming has applications in several domains, such as business management, home computing, and accounts management. These applications can be Character User Interface (CUI) or Graphical User Interface (GUI). Domains in which application of object oriented programming has become prominent includes: o o o o o o o o o o o o o o o o o o Character User Interface based Applications: Graphical User Interface based Applications: Computer Aided Designing/ Manufacturing (CAD/ CAM): Games Image processing Pattern recognition Computer assisted concurrent engineering Computer aided teaching Intelligent systems Data base management systems Web based applications Distributed computing and applications Component based applications Business process reengineering Enterprise resource planning Data security and management Mobile computing Data warehousing and data mining

7

CHAPTER

3

CONCEPT OF OBJECT- ORIENTED PROGRAMMING
The fundamental features of object orientated programming that makes function uniquely the way it does includes the following.

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:

8

What

How

Goals Plans Policy Mechanism Interface/ requirement Implementation

Table 3.1: Equivalent terms reflecting separation.
The abstract view of solving a problem is an essential requirement as we do in a real world problem. Consider an example of the situation in an office. Manager wants to go to a customer’s site. He wants to sign a letter before he leaves. The manager passes the information about the place of destination to the driver who performs the action of moving from the office to the desired site. The manager must know the person who is capable of doing this task even though he may not know driving. The driver takes care of the execution part of driving. In the perspective of the manager, the driver is an employee who knows driving and can take him to the desired place. This abstract information about the driver is enough for the manager. The manager is an officer employed in the office. For the driver the details of the officer like name and designation are enough. This is the abstract information about the officer. The driver uses a car to perform the task. In the perspective of the manager, the type of car such as A/C or non-A/C and brand name may be important. Thus the abstract information of the same entity differs from individual to individual. The essential features of an entity are known as abstraction. A feature may be either an attribute reflecting a property (or state or data) or an operation reflecting a method (or behavior or function) The features such as things in the trunk of a car, the medical history of the manager traveling in the car and the working mechanism of the car engine are not necessary for the driver. The essential features of an entity in the perspective of the user define abstraction. A good abstraction is achieved by having: o meaningful name such as driver reflecting the function o minimum and at the same time complete features o coherent features. Abstraction specifies necessary and sufficient descriptions rather than implementation details. It results in separation of interface and implementation.

9

3.2 Encapsulation.
From the user’s 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 user’s 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.

Table 3.2: Comparison of Abstraction and Encapsulation.

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

4

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.

4.1 A brief history of Java.
James Gosling and other developers at Sun Microsystems, USA, were working on an interactive TV project in the mid-1990s when Gosling became frustrated with the language being used—C++, an object-oriented programming language developed 10 years earlier as an extension of the C language. Gosling studied in his office and created a new language that was suitable for his project and addressed some of the things that frustrated him about C++. Sun’s interactive TV effort failed, but its work on the language had unforeseen applicability to a new medium that was becoming popular at the same time which is the Web. Java was released by Sun in fall 1995. Although most of the language’s features were primitive compared with C++ (and Java today), Java programs called applets could be run as part of web pages on the Netscape Navigator browser. This functionality—the first interactive programming available on the Web— helped publicize the new language and attract several hundred thousand developers in its first six months. Even after the novelty of Java web programming wore off, the overall benefits of the language became clear, and the programmers became more interested in the language. There are more professional Java programmers today than C++ programmers.

4.2 Java Is Platform-Independent.
Platform independence is one of the most significant advantages that Java has over other programming languages, particularly for systems that need to work on many different platforms. Java is platform-independent at both the source and the binary level.
13

o Platform-independence is a program’s capability of moving easily from one computer system to another. At the source level, Java’s primitive data types have consistent sizes across all development platforms. Java’s 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 doesn’t 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 running—so, 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)

Binary File (Pentium)

Your Code__ _______ _________ ____
Compiler (SPARC) Compiler (PowerPC)

Binary File (PowerPC)

Binary File (SPARC)

Figure 4.1. Traditional compiled programs.
14

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)

Java Interpreter (Pentium) Java Bytecode (Platform Independent)

Your Code__ _______ _________ ____
Compiler (SPARC) Compiler (PowerPC)

Java Interpreter (PowerPC) (PowerPC)

(PowerPC) Java Interpreter (SPARC)

Figure 4.2. Java programs.

4.3 Java Is Object-Oriented.
Working with a real object-oriented language and programming environment, however, enables you to take full advantage of object-oriented methodology and its capabilities of creating flexible, modular programs and reusing code. Many of Java’s object-oriented concepts are inherited from C++, the language on which it is based, but it borrows many concepts from other object-oriented languages as well. Like most object-oriented programming languages, Java includes a set of class libraries that provide basic data types, system input and output capabilities, and other utility functions. These basic classes are part of the Java development kit, which also has classes to support networking, common Internet protocols, and user interface toolkit functions. Because these class libraries are written in Java, they are portable across platforms as all Java applications are.

4.4 Java Is Easy to Learn.
In addition to its portability and object-orientation, one of Java’s initial design goals was to be small and simple, and therefore easier to write, easier to compile, easier to debug, and, best of all, easy to learn. Keeping the language
15

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.

4.2 Java Is Distributed and Secure.
Java is used to develop applications that can be distributed among various computers on the network. Java is developed for the distributed environment of the Internet because it supports the various Internet protocols, such as Transmission Control Protocols and Internet Protocol (TCP/IP). Java applications can open and access remote objects on the internet in the same manner as they open and access a local network. Java contains a package, Remote Method Invocation (java.rmi), which is used to build, distributed and client-server based applications. Java has built-in security features that verify that the programs do not perform any destructive task, such as accessing the files on a remote system. Java does not allow the use of explicit pointers. All references to the memory are symbolic references, which mean that the programs cannot access memory locations without proper authorization. When a program is accessed over the internet, it is susceptible to attacks from the virus programs. In Java, the compiled Bytecode is strongly type checked. Any changes made in the Bytecode are flagged as errors and the program does not execute. This ensures the security of the Java program over the Internet.

4.6 Classes and Objects.
The concepts of object-oriented technology must be represented in objectoriented programming languages. Only then, complex problems can be solved in the same manner as they are solved in real world situations. OOP languages

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.

Table 4.1: Comparison of Class and Object

17

CHAPTER

5

WRITING A JAVA PROGRAM
Suppose we want to write a Java program to calculate the area and perimeter of a rectangle of given dimensions

width

length Figure 5.1. A rectangle of given dimensions.

5.1 Identifying and defining the classes.
The first step is to identify what classes will be required o What kinds of entity does our program deal with? o Put another way, what types of object will the program use? o Or, what classes will we need? We will need a class whose instances represent rectangles. The syntax of a Java class declaration is as follows: class <class name> { <list of instance variables> <list of methods> } The first step is to choose a name for the class: class Rectangle { <list of instance variables> <list of methods> } The syntax of a Java instance variable declaration is as follows: private <type> <instance variable name>; /*attributes are usually called instance variables in Java*/

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> }

5.2 Defining methods and constructors in Java.
Typically, a method performs a calculation and returns a result. We need to describe both the type of result returned the calculation to be performed. The syntax of a Java method declaration is as follows: public <result type> <method name> (<parameters>) { <list of local variables> <statement 1>; <statement 2>; ... <statement n>; } We want two methods called calculateArea and calculatePerimeter. Calculating the result involves multiplying the length by the width. Both methods return an int as their result. public int calculateArea () { return length * width; } public int calculatePerimeter () { return (2 * length) + (2 * width); } With these two methods defined our Rectangle class now looks like this:

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

5.3 Writing the Java application.
Now let’s write a Java application that calculates the area and perimeter of a rectangle! Our application will create a rectangle object of the required dimensions, calculate its area, calculate the length of its perimeter, write the area to the screen and write the perimeter to the screen. An application is any class that has a method called main (i.e. it has the method that controls the running by the compiler) Every Java application has the following syntax: class <class name> { public static void main (String args[]) { <list of local variables> <statement 1>; <statement 2>; ... <statement n>; } } A method can have local variables which can only be used by that method. Our application will use three local variables; shape to store the object
21

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 Object-Oriented Programming Basics With Java © 1996-2003 jGuru.com.

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

Sponsor Documents

Or use your account on DocShare.tips

Hide

Forgot your password?

Or register your new account on DocShare.tips

Hide

Lost your password? Please enter your email address. You will receive a link to create a new password.

Back to log-in

Close