Download as pdf or txt
Download as pdf or txt
You are on page 1of 70

Chapter 1

Introduction to
Object Oriented
Programming

By Megha V Gupta, NHITM


Introduction
Object oriented programming is the principle of
design and development of programs using
modular approach.
◦ Object oriented programming approach provides
advantages in creation and development of software for
real life application.
◦ The basic element of object oriented programming is the
data.
◦ The programs are built by combining data and functions
that operate on the data.
◦ Some of the OOP’s languages are C++, Java, C #,
Smalltalk, Perl, and Python.
2
Procedural programming
The procedural programming focuses on
processing of instructions in order to perform a
desired computation.
The top-down concepts to decompose main
functions into lower level components for modular
coding purpose.
Therefore it emphasizes more on doing things like
algorithms.
This technique is used in a conventional
programming language such as C and Pascal.

3
Procedure Oriented Programming

✓ Data move openly around the system from function to function.

Global Data Global Data

Function-1 Function-2 Function-3

Local Data Local Data Local Data

✓ Employs top-down approach in program design.

4
Object –Oriented Programming
✓ Emphasis is on data rather than procedure.
✓ Programs are divided into objects.

Data Data

Functions Functions

Object A Object B

Functions

Data Object C

5
Object oriented programming
Object oriented programming (OOP) is a concept
that combines both the data and the functions that
operate on that data into a single unit called the
object.
An object is a collection of set of data known as
member data and the functions that operate on these
data known as member function.
OOP follows bottom-up design technique.
Class is the major concept that plays important role
in this approach. Class is a template that represents a
group of objects which share common properties
and relationships. 6
Differences
Procedural Programming Object Oriented Programming
Large programs are divided into Programs are divided into
smaller programs known as objects
functions

Data is not hidden and can be Data is hidden and cannot be


accessed by external functions accessed by external functions

Follow top down approach in the Follows bottom-up approach in


program design the program design

Data may communicate with Objects may communicate with


each other through functions each other through functions.
Emphasize is on procedure rather Emphasize is on data rather than
than data procedure

7
History of Java
■ Java was originally designed for interactive television, but it was too advanced technology for the digital
cable television industry at the time.
■ Java team members (also known as Green Team), initiated this project to develop a language for digital
devices such as set-top boxes, televisions, etc.
■ However, it was suited for internet programming. Later, Java technology was incorporated by Netscape.
■ The principles for creating Java programming were "Simple, Robust, Portable, Platform-independent,
Secured, High Performance, Multithreaded, Architecture Neutral, Object-Oriented, Interpreted, and
Dynamic".
■ Java was developed by James Gosling, who is known as the father of Java, in 1995. James Gosling and
his team members started the project in the early '90s.
■ James Gosling - founder of java
■ Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc. There
are given significant points that describe the history of Java.

■ Java is an island of Indonesia where the first coffee was produced (called java coffee).
It is a kind of espresso bean. Java name was chosen by James Gosling while having
coffee near his office.
■ Notice that Java is just a name, not an acronym.
Features of Java
Platform Independent and secured
Multithreading
OOP
■ Object-Oriented Programming is a methodology
or paradigm to design a program using classes and
objects. It simplifies software development and
maintenance by providing some concepts:
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
OOP Concepts

1
7
Objects
Objects are basic building blocks for designing
programs.
An object is a collection of data members and
associated member functions.
An object may represent a person, place or a table of
data.
Each object is identified by

a unique name. Each object

must be a member of a

particular class.

Example: Apple, orange,

mango are the objects of

class fruit.
1
8
Objects
■ Any entity that has state and behavior is known as
an object. For example, a chair, pen, table,
keyboard, bike, etc. It can be physical or logical.
■ An Object can be defined as an instance of a class.
An object contains an address and takes up some
space in memory.
■ Example: A dog is an object because it has states
like color, name, breed, etc. as well as behaviors
like wagging the tail, barking, eating, etc.
q
Encapsulation

Data Encapsulation:
◦ The wrapping of data and functions into a single unit
(class) is called data encapsulation.
◦ Data encapsulation enables data hiding and information
hiding.
Data hiding:
It is a method used in object oriented programming to
hide information within computer code.
Abstraction
• Abstraction refers to the quality of dealing with
ideas rather than events.

• It basically deals with hiding the details and


showing the essential things to the user. If you
look at the image here, whenever we get a call,
we get an option to either pick it up or just
reject it.

• But in reality, there is a lot of code that runs in


the background. So you don’t know the internal
processing of how a call is generated, that’s the
beauty of abstraction.

• Therefore, abstraction helps to reduce


complexity. You can achieve abstraction in two
ways:
a) Abstract Class
Encapsulation
■ The best way to understand encapsulation is to look at
the example of a medical capsule, where the drug is
always safe inside the capsule.
■ Similarly, through encapsulation the methods and
variables of a class are well-hidden and safe.
10
Principles of OOPs

▸Polymorphism
If one task is performed by different ways, it
is known as polymorphism.

For example: To convince the customer


differently, to draw something, like shape,
triangle, rectangle , a cat speaks meow, dog
barks woof, etc.
- Polymorphism present a method that
can have many definitions.
Polymorphism is related to
- Overloading → Compile time
polymorphism/run time polymorphism
- Overriding → Run time polymorphism/
Dynamic polymorphism
- Syntax
getPrice()
getPrice(string name)
Polymorphism
■ Polymorphism means taking many forms, where ‘poly’ means
many and ‘morph’ means forms.
■ It is the ability of a variable, function or object to take on
multiple forms.
■ In other words, polymorphism allows you define one
interface or method and have multiple implementations.
■ Let’s understand this by taking a real-life example and how
this concept fits into Object oriented programming.
Polymorphism
The ability of an operator and function to take
multiple forms is known as Polymorphism.
Polymorphism in Java is of two types:
1.Compile time Polymorphism (Method Overloading)
2. Run time Polymorphism (Method Overriding)
Overloading
Overloading allows objects to have different
meaning depending upon context.
There are two types of overloading viz.
o Operator Overloading
o Function Overloading
When an existing operator operates on new data
type is called operator overloading.
Function overloading means two or more
function have same name, but differ in the
number of arguments or data type of arguments.
Inheritance
Inheritance is the process by which one object
can acquire and use the properties of another
object.
The existing class is known as base class or super class.
The new class is known as derived class or sub class.
The derived class shares some of the properties of the base
class. Therefore a code from a base class can be
reused by a derived class.
Inheritance in Java
Single Inheritance
Hierarchical Inheritance
Inheritance example
Dynamic binding & Message Passing

Dynamic binding:
◦ Binding is the process of connecting one program to another.
◦ Dynamic binding is the process of linking the procedure call
to a specific sequence of code or function at run time or
during the execution of the program.
Message Passing:
◦ In OOP’s, processing is done by sending message to objects.
◦ A message for an object is request for execution of
procedure.
◦ Message passing involves specifying the name of the object,
the name of the function (message) and the information to be
sent.
Language of Internet Programming

Java Applets
Security
Portability
1. Applets:
Special java program that can transmitted over the network and
automatically executed by a java-compatible web browser.
2. Security:
Java compatible web browser can download java applets without
fear of viral infection and malicious agent.
3. Portable:
Java applets can be dynamically downloaded to all the various
types of platforms connected to the internet

41 41
JVM (Java Virtual Machine) Architecture

■ JVM (Java Virtual Machine) is an


abstract machine. It is a
specification that provides
runtime environment in which
java bytecode can be executed.

■ JVMs are available for many


hardware and software
platforms (i.e. JVM is platform
dependent).

Internal architecture of JVM


Java Virtual Machine
✓ Java compiler produces an intermediate code known as byte
code for a machine, known as JVM.
✓ It exists only inside the computer memory.

Java Program Java Compiler Virtual Machine

✓ Machine code is generated by the java interpreter by acting as


an intermediary between the virtual machine and real
machine.

Bytecode Java Interpreter Machine Code


Java Virtual Machine (JVM)
■ Phases of program execution
we write the program, then we compile the program and at last we run
the program.
1) Writing of the program is of course done by java programmer like
you and me.
2) Compilation of program is done by javac compiler, javac is the
primary java compiler included in java development kit (JDK). It takes
java program as input and generates java bytecode as output.
3) In third phase, JVM executes the bytecode generated by compiler.
This is called program run phase.
■ The primary function of JVM is to execute the bytecode produced by
compiler.
■ Each operating system has different JVM, however the output they
produce after execution of bytecode is same across all operating
systems.
■ That is why we call java as platform independent language.
Basics of Java Environments
Java programs normally undergo five phases
Edit
Programmer writes program (and stores program on disk)
Compile
Compiler creates bytecodes from program
Load
Class loader stores bytecodes in memory
Verify
Verifier ensures bytecodes do not violate security
requirements
Execute
Interpreter translates bytecodes into machine language

45 45
Java Environment
Development tools-part of java development kit (JDK).
Classes and methods-part of Java Standard Library (JSL),
also known as Application Programming Interface (API).
1. JDK:
Appletviewer ( for viewing applets)
Javac (Compiler)
Java (Interpreter)
Javap (Java disassembler)
Javah (for C header files)
Javadoc ( for creating HTML description)
Jdb (Java Debugger)
46 46
Java Environment
2. Application Package Interface (API)
Contains hundreds of classes and methods grouped into
several functional packages:
Language Support Package
Utility Packages
Input/Output Packages
Networking Packages
AWT Package
Applet Package

47 47
Basic Structure of Java Program

Main Method Class


The main method is from where
the execution actually starts and
follows the order specified for the
following statements.
Java Program
Java Source
Code

Java Compiler

Applet Type Application Type

Java Enabled
Browser Java Interpreter

Output
Output
49
First Java Program-Example 1

/*This is a simple java program*/


class Example
{
public static void main (String args[])
{
System.out.println (“This is a simple Java program”);
}
}

50
Simple Java Program-Some important points

✓ public: Access specifier. main() must be made public, since it


must be called by code defined outside it’s class.
✓ Static: It is required because main() is called without creating
an object of it’s class
✓ String args[]: An array of objects of type String class. Each
object of type string contains a character string. It is used to
manipulate command line argument.
✓ Java is case sensitive.
✓ System predefined class that refers to system.
out It is static data member of System class
println() It is a member of out object

8/1/2023
51
The requirement for Java Hello
World Example
• Install the JDK if you don't have installed
it, download the JDK and install it.
• Set path of the jdk/bin directory.
• Create the java program
• Compile and run the java program
Creating Hello World Example

class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
} To compile: javac Simple.java Output:Hello Java

To execute: java Simple


Java is a Strongly typed Language

✓ Every variable and expression has a strongly defined type.


✓ All assignments are checked for type compatibility.
✓ Java compiler checks all expressions and parameters to ensure
that the types are compatible.

8/1/2023 54
54
The Primitive Types
✓ There are exactly eight primitive data types in Java
✓ Four of them represent whole valued signed numbers:
✓ byte, short, int, long
✓ Two of them represent floating point numbers:
✓ float, double
✓ One of them represents characters:
✓ char
✓ And one of them represents boolean values:
✓ boolean

8/1/2023 55
55
Numeric Primitive Types

✓ The difference between the various numeric primitive types is


their size, and therefore the values they can store:

Type Storage Min Value Max Value

byte 8 bits -128 127


short 16 bits -32,768 32,767
int 32 bits -2,147,483,648 2,147,483,647
long 64 bits < -9 x 1018 > 9 x 1018

float 32 bits +/- 3.4 x 1038 with 7 significant digits


double 64 bits +/- 1.7 x 10308 with 15 significant digits
8/1/2023 56
56
Character Primitive Type
✓ It uses unicode to represent character.
✓ The char type is unsigned 16 bit values ranging from 0 to 65536.
✓ ASCII still ranges from 0 to 127.
Example:
class test
{ public static void main (String args[])
{
char ch1, ch2;
ch1=88;
ch2=‘Y’;
System.out.println (“ch1 and ch2: “ + ch1+” “+ch2);
}
}
Output: ch1 and ch2: X Y
8/1/2023 57
57
Character Primitive Type
Example:
class test
{
public static void main (String args[])
{
char ch1;
ch1= ‘X’;
Sytem.out.println (“ch contains “+ch1);
ch1++;
System.out.println (“ch1 is now “ + ch1);
}
}
Output:
ch1 contains X
Ch1 is now Y

8/1/2023 58
58
Booleans
✓ Size is 1 bit – two value: true and false.
✓ This type is returned by all relational operators.
✓ Example:
boolean b;
b= true;
1. System.out.println(“b is “+b);
2. System.out.println(“10>9 is “ +(10>9));
Output:
b is true
10>9 is true

8/1/2023 59
59
Literals
✓ Integer Literals
1. base 10 – 1,2,43 etc.
2. base 8 – octal values are denoted in java by a leading 0.
3. base 16 – hexadecimal values are denoted by leading 0x
or 0X.
■ Any whole number is by default integer (32 bits).
■ To specify a long literal, the number should appended with
an upper- or lowercase L.

8/1/2023 60
60
Literals
✓ Floating point Literals
1. Standard Notation – 3.14159, 0.6667, 2.0 etc.
2. Scientific Notation – 6.022E23, 2e+100.
■ Floating point literals are by default of type double.
■ To specify a float literal, we must append an F or f to the constant.
✓ Boolean Literals
■ Two values – true and false.
■ True is not equal 1 and false is not equal to 0.
■ They can be assigned to variable declared as boolean.

8/1/2023 61
61
Literals
✓ Character Literals:
■ A literal character is represented inside a pair of single quotes.
Escape sequence Unicode Description
Representation
1. \’ \u0027 Single quote
2. \” \u0022 Double quote
3. \\ \u005c Backslash
4. \r \u000d Carriage Return
5. \n \u000a New line
6. \f \u000b Form feed
7. \t \u0009 Tab
8. \b \u0008 Backspace
9. \ddd Octal Character
10. \uxxxx Hexadecimal Unicode
character

8/1/2023 62
62
Literals

✓ String Literals
■ A sequence of characters between a pair of double
quotes.
■ In java string must begin and end on the same line.

8/1/2023 63
63
Variables

✓ Variable is a name for a location in memory.


✓ Declaring a variable:
type identifier [=value][,identifier [=value]….];
✓ The initialization expression must result in a value of the same or
compatible type as that specified for the variable.
✓ When a variable is not initialized, the value of that variable is
undefined.

8/1/2023 64
64
Operators

1. subscript [ ], call ( ), member access .


2. pre/post-increment ++ --, boolean complement !, bitwise
complement ~, unary + -, type cast (type), object creation
new
3. * / %
4. binary + - (+ also concatenates strings)
5. signed shift << >>, unsigned shift >>>
6. comparison < <= > >=, class test instanceof
7. equality comparison == !=
8. bitwise and &
9. bitwise or |

65
Operators

11. logical (sequential) and &&


12. logical (sequential) or ||
13. conditional cond ? true-expr : false-expr
14. assignment =, compound assignment += -= *= /= <<=
>>= >>>= &= |=

66
Declaring and Setting Variables

■ int square;
square = n * n;
■ double cube = n * (double)square;
– Can generally declare local variables where they are
initialized
– All variables get a safe initial value anyway (zero/null)

67
Referencing and Creating
Objects
■ You can declare reference variables
– They reference objects of specified types
■ Two reference variables can reference the same object
■ The new operator creates an instance of a class
■ A constructor executes when a new object is created
■ Example: String greeting = ″hello″;

68
Java Control Statements

■ A group of statements executed in order is written


– { stmt1; stmt2; ...; stmtN; }
■ The statements execute in the order 1, 2, ..., N
■ Control statements alter this sequential flow of execution

69
Java Control Statements (continued)

70

You might also like