0% found this document useful (0 votes)
49 views23 pages

UNIT 1: oop

This document introduces Object-Oriented Programming (OOP) with a focus on Java, discussing fundamental programming structures, paradigms, and basic concepts. It covers essential topics such as data types, variables, control flow, and the main method in Java, while also comparing OOP with procedural programming. The unit aims to equip learners with an understanding of OOP principles, advantages, and the ability to differentiate between various programming paradigms.

Uploaded by

amanuel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views23 pages

UNIT 1: oop

This document introduces Object-Oriented Programming (OOP) with a focus on Java, discussing fundamental programming structures, paradigms, and basic concepts. It covers essential topics such as data types, variables, control flow, and the main method in Java, while also comparing OOP with procedural programming. The unit aims to equip learners with an understanding of OOP principles, advantages, and the ability to differentiate between various programming paradigms.

Uploaded by

amanuel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

UNIT 1: INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

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

1.0. AIMS AND OBJECTIVES

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:

• Understand overviews of object oriented principles


• Differentiate the advantages and disadvantages of using Object Oriented
Programming
• Know the basic concepts behind object oriented programming

1
1.1. INTRODUCTION TO FUNDAMENTAL STRUCTURES
STRUCTURES IN JAVA

Object-Oriented Programming (OOP) is the term used to describe a programming approach


based on objects and classes. The object-oriented paradigm allows us to organize software
as a collection of objects that consist of both data and behavior. This is in contrast to
conventional functional programming practice that only loosely connects data and
behavior.
In this section, we will learn

• A Simple Java Program


• How to use Comments
• Data Types
• Variables declarations
• Assignments and Initializations
• Operators and Strings
• Control Flow and Arrays

A Simple Java Program

We'll start with a simple application and it simply prints a message to the console.

// A first program in Java


public class Hello
{
public static void main( String args[])
{
System.out.println( "Hello, world!" );
/* It prints Hello, world! */
}
}
What to note about our example?

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)

The main() method

• Every Java application must have a main() method


• Curly braces ({}) mark the beginning and end of a block
• All Java main methods are public static void

Java classes and methods

• 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()

• Contains a statement that outputs a single line of text to the console


• We use the System.out object and ask it to use its println method
• Java always uses the general syntax
object.method(argument_list) for its function calls
• The println method works with a string and displays it on the console
• There is also a print method in System.out which doesn't add a newline at the end

Command-line arguments:

• Although in Java, as in C++, the main method receives an array of command-line


arguments, the array syntax is different
• A String[] is an array of strings, and so args denotes an array of strings
• Unlike C++, the name of the program is not stored in the args array

Comments

• Java has three styles of comments


• // begins a comment that runs from the // to the end of the line
• /* begins a comment that terminates with the character pair */
• /** and **/ delimit a special type of comment which is processed by
the javadoc automatic documentation tool
• /* */ comments do not nest in Java

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

int 4 byte -231 to +231-1

short 2 byte -32,768 to +32,767

long 8 byte -263 to +263-1

byte 1 byte -128 to +127

• 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

Type Size Range

Float 4 byte +/-(10-38 to 10+38) (6 to 7 significant digits)

Double 8 byte +/-(10-308 to 10+308) (15 significant digits)

• 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

The Boolean Type

• The Boolean type has two values, false and true


• It is similar the C++ type bool, except that in Java, you cannot convert between
numbers and Boolean values, not even with a cast.

5
Special Characters

Escape Sequence Name Unicode Value


\b Backspace \u0008
\t Tab \u0009
\n linefeed \u000A
\r Carriage return \u000D
\” Quote mark \u0022
\’ apostrophe \u0027
\\ backslash \u005C

• 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

• Java uses variables in a way similar to that of C++


• Naming rules:
• Variable name must begin with a letter and be a sequence of letters or digits
• A "letter" is A-Z, a-z, _ (underscore), or any Unicode character that denotes a
letter in a language -- Germans could use 'ä', Greeks could use 'µ', etc.
• A "digit" is 0-9 or any Unicode character that denotes a digit in a language
• All characters in the name of a variable are significant and case is significant
• There is no upper limit to the length of a variable name

Conversions between Numeric Types


Automatic promotions of numeric types work as they do in C++. Demotion is done through
explicit casts in the same way that C does it (the C++ form is not available)
6
double x = 9.9997;
int y = (int) x; // notint(x) à this stores the value 9 in y

• You cannot cast between boolean values and any numeric types

Constants

In Java, you use the keyword final to denote a constant.

public class UsesConstants


{
public static void main(String[] args)
{
final double CM = 2.54;
double paperWidth = 8.5;
System.out.println("Paper width in cms: " + paperWidth*CM);
}
}

The reserved word final indicates that you can assign to the variable once, then its value is
set once and for all

Static Constants

• It is probably more common in Java to want a constant that is available to multiple


methods inside a single class (a class constant)
• Class constants are defined with the keywords static final

public class UsesConstants


{
public static void main(String[] args)
{
final double CM = 2.54;
double paperWidth = 8.5;
System.out.println("Paper width in cms: " + paperWidth*CM);
}
}

• 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

• The usual operators + - * / % are used in Java


• As in C, +=, -=, *=, /=, %= are also available
• The usual way of doing exponentiation is via the statement:
o double y = Math.pow(x, a);
• Note: The Math class in Java has a large number of functions an engineer would
need (constants for pi and e, sqrt , ln, exp, rounding, abs, max, min, etc.)

Other Operators

• Increment and Decrement Operators (The ++ and -- operators are used as in C)


• Relational and Boolean Operators
o ==, !=, >, <, <=, >= are used in comparisons
o &&, ||, and ! are the Boolean operators
o Boolean operators are evaluated in short circuit fashion
• Unlike C, Java does not have a comma operator
o However, you can use a comma-separated list of expressions in the first and
third slot of a for statement

Bitwise Operators

• & ("and"), | ("or"), ^ ("xor"), ~ ("not") are the bitwise operators.


e.g. int fourthBitFromRight = (foo & 8) / 8; à gives you a 1 if bit 3 of foo is 1, and
0 if it is 0
• >> and << are the right and left bit shift operators

int fourthBitFromRight = (foo & (1 << 3)) >>3;


• >> does right shift with sign extension
• >>> does right shift with zero-fill
• (There is no >>> operator in C, and the action of >> is not well defined, so it only
works correctly for positive integers)

8
Strings

• Java does not have a built-in string type


• The standard Java library contains a predefined class called String
• Each quoted string is an instance of the String class
String e = ""; // an empty string
String greeting = "Hello";

Concatenation

• Java allows you to use the + sign to concatenate two strings together

String part1 = "Hello";


String part2 = "world";
String message = part1 + part2;

• 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

String rating = "PG" + 13; à //sets rating to the string "PG13"


Substrings

• You can extract a substring from a larger string with the substring method of the
String class

String machine = "computer";


String s = machine.substring(1,4);
//creates a string consisting of the characters "omp"

• The first argument to substring is the starting position of the substring


• The second argument is the first position that you do not want to copy
• This seems peculiar, but it is easy to compute the length of the substring
• s. substring (a, b) always has length b-a

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

• A block (or compound statement) is a sequence of statements enclosed in curly


braces
• A block allows you to use multiple statements as a unit
• In Java, unlike C, it not possible to declare identically named variables in two nested
blocks

public static void main(String[] args)


{
int n;
{
int k;
int n; // error -- can't redefine n in inner block
}
}

Conditional Statements

• if and if-else statements are identical to those of C/C++


• Because of the short-circuit boolean expression evaluation built-in to Java,

if (x !=0 && 1/x > 0) // no division by zero

(does not evaluate 1/x if x is zero, and so cannot lead to a divide-by-zero error)

• Java also supports the ternary? Operator à condition ? e1 : e2

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

1. Explain briefly the fundamental structures in java?


_________________________________________________________________________________________________
________________________________________________________________________________________________
__________________________________________________

1.2. OBJECT ORIENTED


ORIENTED PROGRAMMING PARADIGMS
PARADIGMS

A programming paradigm is a style or "way" of programming. Some languages make it easy


to write in some paradigms but not others. A programming paradigm is basically a model of
programming based on distinct concepts that shapes the way programmers design,
organize and write programs. It is a style of building the structure and elements of
computer programs. Programming paradigm is a way of conceptualizing what is means to
perform computation and how tasks to be carried out on a computer should be structured
and organized.
Types of programming paradigm
Some of the more common paradigms are:
• Imperative — Control flow is an explicit sequence of commands.
• Declarative — Programs state the result you want, not how to get it.
• Structured — Programs have clean, goto-free, nested control structures.
• Procedural — Imperative programming with procedure calls.
• Object-Oriented — Computation is effected by sending messages to objects; objects
have state and behavior.
• Event-Driven — Control flow is determined by asynchronous actions (from
humans or sensors).
Procedure oriented programming
In the procedure oriented approach, the problem is viewed as the sequence of things to be
done such as reading, calculating and printing such as COBOL, FORTRAN and C. The
primary focus is on functions. A typical structure for procedural programming is shown in
the figure below. The technique of hierarchical decomposition has been used to specify the
tasks to be completed for solving a problem.

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.

Object-Oriented Programming Paradigm


The major motivating factor in the invention of object-oriented approach is to remove
some of the flaws encountered in the procedural approach. OOP treats data as a critical
element in the program development and does not allow it to flow freely around the
system. It ties data more closely to the function that operate on it, and protects it from
accidental modification from outside function. OOP allows decomposition of a problem
into a number of entities called objects and then builds data and function around these
objects. The organization of data and function in object-oriented programs is shown in the
figure below. The data of an object can be accessed only by the function associated with
that object. However, function of one object can access the function of other objects.

Some of the features of object oriented programming are:


• Emphasis is on data rather than procedure.
• Programs are divided into what are known as objects.

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.

A simple event-driven programming paradigm

Check your progress-2

1. Explain the difference between object oriented programming paradigms and


procedural programming paradigms?
_________________________________________________________________________________________________
_________________________________________________________________________________________________
____________________________________________________

1.3. BASIC CONCEPTS


CONCEPTS OF OBJECT ORIENTED
ORIENTED PROGRAMMING

It is necessary to understand some of the concepts used extensively in object-oriented


programming. These include:
• Objects and Classes
• Data abstraction and encapsulation
• Inheritance and Polymorphism
• Dynamic binding
• Message passing
We shall discuss these concepts in some detail in this section.

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.

Data Abstraction and Encapsulation


The wrapping up of data and function into a single unit (called class) is known as
encapsulation. The data is not accessible to the outside world, and only those functions
which are wrapped in the class can access it. These functions provide the interface between
the object’s data and the program. This insulation of the data from direct access by the
program is called data hiding or information hiding.

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.

Polymorphism is extensively used in implementing inheritance.

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++.

Some of the basic advantages of using object oriented programming are:

o Its based on real world problem (classes and objects)


o Complexity of software will be easily reduced and managed.

22
o Object-oriented system can be easily upgraded from small to large system.
o Message passing is much simpler and easier

1.6. MODEL EXAMINATION QUESTIONS.


QUESTIONS.

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.

II: Short Answer Questions

1. Explain the advantages and disadvantages of using object oriented programming?


2. List some of the characteristics of procedural programming?
3. Write a simple java program and explain the structure in detail?
4. Distinguish between the following basic concepts of OOP briefly with example:
a. Objects and Classes
b. Abstraction and Encapsulation

23

You might also like