UNIT 1: oop
UNIT 1: oop
Contents
1.0 Aims and Objectives
1.1. Introduction to Fundamental programming structures in Java
1.2. Object Oriented Programming Paradigms
Paradigms
1.3. Basic Concepts of Object oriented programming
1.4. Overview of Java programming
1.5. Summary
1.6. Model Examination Questions
This unit discusses different types of programming paradigms such as object object
oriented, procedural, event driven and declarative. We will focus on object oriented
paradigms, specifically on it’s principles, structures (the main() method, primitive data
types, control flows and so on).
After you have studied this unit, you will be able to:
1
1.1. INTRODUCTION TO FUNDAMENTAL STRUCTURES
STRUCTURES IN JAVA
We'll start with a simple application and it simply prints a message to the console.
Java is case sensitive, like C++, so watch your spelling and capitalization. The keyword
public is called an access modifier. These modifiers control what other parts of a program
2
can use this code. The keyword class is there because, unlike C++, everything in a Java
program is enclosed in a class.
Names in Java
Following the keyword class is the name of the class in which the rules for names are
similar to that of C++.
• Names must begin with a letter and after that they can have any combination of
letters and digits
• The length is essentially unlimited
• You cannot use a Java reserved word (e.g. if, public, like C++'s reserved words). The
convention is that class names begin with initial caps
• The file name for the source code must be exactly the same as the name of the public
class, with the extension .java appended (i.e., Hello.java, not hello.java)
• Java classes are similar to C++ classes, but there are a few differences
• In Java, all functions are member functions of some class (and they are
called methods)
• In Java, you have a shell class for the main method
• In Java, as in C++, static member functions are those defined inside a class, but do
not operate on objects
• The main method in Java is always static
3
The Body of main()
Command-line arguments:
Comments
Data Types
• Java is a strongly typed language and each variable must have a declared type
• There are eight primitive types
o Six are numeric types (4 integers and 2 floating-point types)
o One is the character type char
o One is a Boolean type
4
Integers
Type Size Range
• These ranges are the same no matter what machine you are running on (unlike C++)
• Java does not have any unsigned types
• Long integer numbers have the suffix L (40000000L)
• Hexadecimal numbers have a prefix of 0x ( 0xCAFE278 )
Floating-Point Types
• You will usually want to use double because of its extended range and greater
precision
• Numbers of type float have a suffix F
• Numbers without a suffix are always considered double, but you may use a D suffix
• All floating-point types follow the IEEE 754 specification
5
Special Characters
• In C++, char denotes an integral type (1 byte integer) in the range 0..255 or -
128..127
• In Java, char is not a number -- converting numbers to characters requires an
explicit cast, however, characters are automatically promoted to integers without a
cast
Variables
• You cannot cast between boolean values and any numeric types
Constants
The reserved word final indicates that you can assign to the variable once, then its value is
set once and for all
Static Constants
• Note that the definition of the class constant appears outside the main method
• Note: const is a reserved Java keyword, but it is not currently used for anything
7
Operators
Other Operators
Bitwise Operators
8
Strings
Concatenation
• Java allows you to use the + sign to concatenate two strings together
• The above code makes the value of the string object message "Helloworld"
• When you concatenate a string with a value that is not a string, the latter is
converted to a string
• You can extract a substring from a larger string with the substring method of the
String class
Control Flow
• Java control flow constructs are very similar to those of C and C++, with a few minor
exceptions
9
• We will emphasize what the exceptions are
• Java has no goto, but it does have a "labeled" version of break that you can use to
break out of a nested loop (about the only place where a goto should be used
anyway)
Block Scope
Conditional Statements
(does not evaluate 1/x if x is zero, and so cannot lead to a divide-by-zero error)
Looping Structures
• The while loop does the test at the top, just as it does in C++
• The do-while does the test at the bottom, also as in C++
• The for loop is used for counter-controlled loops, as in C++
10
Check your progress-1
11
Procedure oriented programming basically consists of writing a list of instructions for the
computer to follow, and organizing these instructions into groups known as functions. We
normally use flowcharts to organize these actions and represent the flow of control from
one action to another.
In a multi-function program, many important data items are placed as global so that they
may be accessed by all the functions. Each function may have its own local data. Global
data are more vulnerable to an inadvertent change by a function. In a large program it is
very difficult to identify what data is used by which function. In case we need to revise an
external data structure, we also need to revise all functions that access the data. This
provides an opportunity for bugs to creep in.
Another serious drawback with the procedural approach is that we do not model real
world problems very well. This is because functions are action-oriented and do not really
corresponding to the element of the problem.
12
Some Characteristics exhibited by procedure-oriented programming are:
• Emphasis is on doing things (algorithms).
• Large programs are divided into smaller programs known as functions.
• Most of the functions share global data.
• Data move openly around the system from function to function.
• Functions transform data from one form to another.
• Employs top-down approach in program design.
13
• Data structures are designed such that they characterize the objects.
• Functions that operate on the data of an object are ties together in the data structure.
• Data is hidden and cannot be accessed by external function.
• Objects may communicate with each other through function.
• New data and functions can be easily added whenever necessary.
• Follows bottom up approach in program design.
Event-driven programming
Event-driven programming is a programming paradigm in which the flow of program
execution is determined by events - for example a user action such as a mouse click, key
press, or a message from the operating system or another program. An event-driven
application is designed to detect events as they occur, and then deal with them using an
appropriate event-handling procedure. Event-driven programs can be written in any
programming language, although some languages (Visual Basic for example) are
specifically designed to facilitate event-driven programming, and provide an integrated
development environment (IDE) that partially automates the production of code, and
provides a comprehensive selection of built-in objects and controls, each of which can
respond to a range of events. Virtually all object-oriented and visual languages support
event-driven programming. Visual Basic, Visual C++ and Java are examples of such
languages.
A visual programming IDE such as VB.Net provides much of the code for detecting events
automatically when a new application is created. The programmer can therefore
concentrate on issues such as interface design, which involves adding controls such as
command buttons, text boxes, and labels to standard forms (a form represents an
application's workspace or window). Once the user interface is substantially complete, the
programmer can add event-handling code to each control as required. Many visual
programming environments will even provide code templates for event-handlers, so the
programmer only needs to provide the code that defines the action the program should
take when the event occurs. Each event-handler is usually bound to a specific object or
control on a form. Any additional subroutines, methods, or function procedures required
14
are usually placed in a separate code module, and can be called from other parts of the
program as and when needed.
15
Objects
Objects are the basic run time entities in an object-oriented system. They may represent a
person, a place, a bank account, a table of data or any item that the program has to handle.
They may also represent user-defined data such as vectors, time and lists. Programming
problem is analyzed in term of objects and the nature of communication between them.
Program objects should be chosen such that they match closely with the real-world objects.
Objects take up space in the memory and have an associated address like a record in Pascal,
or a structure in c.
Although different author represents them differently the figure below shows two
notations that are popularly used in object-oriented analysis and design.
Classes
A class is a collection of objects similar types. For examples, Mango, Apple and orange are
members of class fruit. Classes are user-defined that types and behave like the built-in
types of a programming language. If fruit has been defining as a class, then the statement
Fruit Mango; will create an object mango belonging to the class fruit.
16
Abstraction refers to the act of representing essential features without including the
background details or explanation. Classes use the concept of abstraction and are defined
as a list of abstract attributes such as size, wait, and cost, and function operate on these
attributes. They encapsulate all the essential properties of the object that are to be created.
The attributes are sometime called data members because they hold information. The
functions that operate on these data are sometimes called methods or member function.
Since the classes use the concept of data abstraction, they are known as Abstract Data
Types (ADT).
Inheritance
Inheritance is the process by which objects of one class acquired the properties of objects
of another classes. It supports the concept of hierarchical classification. In OOP, the concept
of inheritance provides the idea of reusability.
Note that each sub-class defines only those features that are unique to it. Without the use of
classification, each class would have to explicitly include all of its features.
Polymorphism
Polymorphism is another important OOP concept. Polymorphism, a Greek term, means the
ability to take more than on form. An operation may exhibit different behavior with
different instances. The behavior depends upon the types of data used in the operation. For
17
example, consider the operation of addition. For two numbers, the operation will generate
a sum. If the operands are strings, then the operation would produce a third string by
concatenation. The process of making an operator to exhibit different behaviors in different
instances is known as operator overloading.
The figure below illustrates that a single function name can be used to handle different
number and different types of argument. This is something similar to a particular word
having several different meanings depending upon the context. Using a single function
name to perform different type of task is known as function overloading.
Dynamic Binding
Binding refers to the linking of a procedure call to the code to be executed in response to
the call. Dynamic binding means that the code associated with a given procedure call is not
known until the time of the call at run time. A function call associated with a polymorphic
reference depends on the dynamic type of that reference.
Message Passing
An object-oriented program consists of a set of objects that communicate with each other.
The process of programming in an object-oriented language, involves the following basic
steps:
1. Creating classes that define object and their behavior,
18
2. Creating objects from class definitions, and
3. Establishing communication among objects.
Objects communicate with one another by sending and receiving information much the
same way as people pass messages to one another. The concept of message passing makes
it easier to talk about building systems that directly model or simulate their real-world
counterparts.
Message passing involves specifying the name of object, the name of the function (message)
and the information to be sent. Example:
Object has a life cycle. They can be created and destroyed. Communication with an object is
feasible as long as it is alive.
Benefits of OOP
OOP offers several benefits to both the program designer and the user. Object-Orientation
contributes to the solution of many problems associated with the development and quality
of software products. The new technology promises greater programmer productivity,
better quality of software and lesser maintenance cost. The principal advantages are:
• Through inheritance, we can eliminate redundant code.
• We can build programs from the standard working modules that communicate with
one another, rather than having to start writing the code from scratch. This leads to
saving of development time and higher productivity.
• The principle of data hiding helps the programmer to build secure program that
cannot be invaded by code in other parts of a programs.
19
• It is possible to have multiple instances of an object to co-exist without any
interference.
• It is possible to map object in the problem domain to those in the program.
• It is easy to partition the work in a project based on objects.
• Object-oriented system can be easily upgraded from small to large system.
• Message passing techniques for communication between objects makes to interface
descriptions with external systems much simpler.
• Software complexity can be easily managed.
Check your progress-3
1. List and explain the basic concepts behind object oriented programming?
_________________________________________________________________________________________________
_________________________________________________________________________________________________
__________________________________________________
1.4. OVERVIEW
OVERVIEW OF JAVA PROGRAMMING
PROGRAMMING
What is Java?
Java Technology consists of:
• Java Language
• Java Platform
• Java Tools
Java technology
20
Java language is a general-purpose programming language. It can be used to develop
software for mobile devices, browser-run applets, games, as well as desktop, enterprise
(server-side), and scientific applications.
Java platform consists of Java virtual machine (JVM) responsible for hardware abstraction,
and a set of libraries that gives Java a rich foundation.
Java tools include the Java compiler as well as various other helper applications that are
used for day-to-day development (e.g. debugger).
Why Java?
Object Oriented
Everything in Java is coded using OO principles. This facilitates code modularization,
reusability, testability, and performance.
Interpreted/Portable
Java source is compiled into platform-independent byte code, which is then
interpreted (compiled into native-code) at runtime. Java’s slogan is "Write Once,
Run Everywhere"
Simple
Java has a familiar syntax, automatic memory management, exception handling,
single inheritance, standardized documentation, and a very rich set of libraries (no
need to reinvent the wheel).
Secure/Robust
Due to its support for strong type checking, exception handling, and memory
management, Java is immune to buffer- overruns, leaked memory, illegal data
access. Additionally, Java comes with a Security Manager that provides a sand-box
execution model.
Scalable
Thanks to its overall design, Java is scalable both in terms of
performance/throughput, and as a development environment. A single user can play
a Java game on a mobile phone, or millions of users can shop though a Java-based e-
commerce enterprise application.
21
High-performance/Multi-threaded
With its Hotspot Just-in-Time compiler, Java can achieve (or exceed) performance of
native applications. Java supports multi-threaded development out-of-the-box.
Dynamic
Java can load application components at run-time even if it knows nothing about
them. Each class has a run-time representation.
Distributed
Java comes with support for networking, as well as for invoking methods on remote
(distributed) objects through RMI.
There are two types of Java programs:
1. Applications - Java programs that run directly on your machine.
• Applications must have a main().
• Java applications are compiled using the javac command and run using the java
command.
2. Applets - Java programs that can run over the Internet. The standard client/server
model is used when the Applet is executed. The server stores the Java Applet, which is
sent to the client machine running the browser, where the Applet is then run.
• Applets do not require a main(), but in general will have a paint().
• An Applet also requires an HTML file before it can be executed.
• Java Applets are also compiled using the javac command, but are are run either with
a browser or with the appletviewer command.
1.5. SUMMARY
In this chapter we have tried to cover the basics of object oriented programming. We also
have seen the fundamental programming structures in java such as the main () function,
comments, data types and variables declarations similar to C++.
22
o Object-oriented system can be easily upgraded from small to large system.
o Message passing is much simpler and easier
I: True/False questions
1. OOP allows decomposition of a problem into a number of entities called objects
and then builds data and function around these objects.
2. Java programming is case sensitive, like C++.
3. In object oriented programming the primary focus is function.
4. The main advantages and goals of object oriented software engineering are to
make complex software faster to develop and easier to maintain.
5. Polymorphism is the process by which objects of one class acquired the
properties of objects of another classes.
23