Introduction to OOP
Introduction to Object Oriented Programming
• As the name suggest, object oriented programming refers to language that uses
objects in programming.
• OOP binds together the data and methods in the form of an object.
• OOP allow us to combine the data and methods into specific group called
class.
• OOP aims to implement real-world entities like inheritance, encapsulation,
polymorphism, abstraction etc. in programming.
• OOP improves code readability and reusability by defining a program
efficiently.
• The new technology promises greater programmer productivity, better quality
of software and lesser maintenance cost.
• OOP systems can be easily upgraded from small to large systems.
• Examples: JAVA, C++, [Link], C#.NET
Features of OOP
• Emphasis is on data rather than procedures.
• Programs are divided into what are known as objects.
• Data structures are designed such that they characterize the objects.
• Methods that operates on the data of an object are tied together in the data
structure.
• Data is hidden and can not be accessed by external functions.
• Objects may communicate with each other through methods.
• New data and methods can be easily added whenever necessary.
• Follows bottom- up approach in program design.
• Example: JAVA, C++, [Link], C#.NET.
OOPs concepts
1. Objects:
➢An object can be defined as an instance of a class. It is a run –time entity.
➢Any entity that has state (Attribute) and behaviour is known as an object.
➢It can be physical or logical.
➢An object contains an address and takes up some space in memory.
➢Objects can communicate without knowing the details of each other's data or
code.
➢Example: A dog is an object, because it has state like color, name, breed etc. as
well as behaviour like wagging the tail, barking , eating etc.
2. Class :
➢Collection of objects is called class.
➢A class can also be defined as a blueprint from which you can create an individual
object.
➢Class is a logical class entity.
➢Class doesn’t consume any space.
➢Class is a user-defined data type.
➢Class contains data members and methods.
➢Example: Mango is object which belongs to class fruit.
3. Encapsulation:
➢Wrapping up of data and methods into a single unit (called class) is known as
encapsulation.
➢The data is not accessible to the outside world and only those methods, which are
wrapped in the class can access it. Therefore, it is also called as Data hiding.
Fig : Encapsulation
➢Example: Multiple parts like Steering, wheels engine etc which binds together to
form a single object that is car.
4. Abstraction:
➢Abstraction refers to the act of representing essential features without including
the background details or explanations.
➢Example : We drive car without knowing the internal part's details about how the
engine works and how the car stops on applying brakes.
5. Inheritance:
➢Deriving a new class from existing class.
➢Inheritance is the process by which objects of one class acquire the properties of
objects of another class.
➢Here, we have two types of classes: base class and the other is subclass.
➢A subclass inherits all the properties of base class.
➢Eg. Cars, scooters, planes and ships all have an engine and speedometer. These are
characteristics of vehicles. Each subclass has its own characteristic feature, e.g.
motorcycle have disk breaking system, while planes have hydraulic braking
system. A car can run only on the surface , while a plane can fly in air and a ship
sails over water.
Fig . Inheritance
➢Inheritance provides the idea of reusability. This means that we can add additional
features to an existing class without modifying it.
➢Types of inheritance: single level, multilevel, multiple, hierarchical level, hybrid
inheritance.
6. Polymorphism:
➢Polymorphism means the ability to take more than one form.
➢ The same thing being used in different forms.
➢For example , an operation may exhibit different behaviour in different instances.
➢The behaviour depends upon the types of data used in the operation.
➢For example, consider the operation of addition for two numbers, the operation
will generate the sum. If the operands are strings, then the operation would
produce a third string by concatenation.
➢Following fig. illustrates that a single function name can be used to handle
different number and different types of arguments.
Fig . Polymorphism
➢Example: A Boy can be a so student, a player and a writer, so that this boy can
play different role as per the situations.
❑ Types of polymorphism:
i. Compile time polymorphism:-
• Also known as static polymorphism.
• It is achieved through Method overloading or operator overloading. However,
JAVA does not support operator overloading.
• Method overloading is when a class has multiple methods with the same name;
but the number , type , and order of parameters and return type of methods are
different.
ii. Runtime polymorphism
• Also known as Dynamic Binding.
• It can be achieved by Method overriding.
• It can be achieved through functions and not by the data members.
• Method overriding is done when a child or a sub class has method with the same
name, parameters and return type as the parent or the super class; then that
function overrides the function in the superclass.
7. Message Passing /communication:
➢Message passing in terms of computers is communication between processes.
➢Message passing in JAVA is like sending an object i.e. message from one thread
(lightweight process) to another thread.
➢It is used when threads do not have shared memory and are unable to share
monitors or any other shared variable to communicate.
Fig . Network of object communicating between them
➢A message for an object is a request for execution of a procedure and therefore
will invoke a method (procedure) in the receiving object that generates the desired
result.
Sending object Receiving object
Fig . Message triggers a method
➢Message passing involves specifying the name of the Object, the name of the
method (message) and the information to be sent.
For example:
Consider the Statement:
Employee . Salary (name);
Object Message Information (parameter)
Object have life cycle. They can be created and destroyed communication with an
object is feasible as long as it is alive.
• BENEFITS OF OOP:
1. Through inheritance we can eliminate redundant code and extend the use of existing
classes.
2. 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.
3. The principle of data hiding helps the programmer to build secure programs that
cannot be invaded by code in other parts of the program.
4. It is possible to have multiple objects to coexist without any interference.
5. It is possible to map objects in the problem domain to those objects in the program.
6. It is easy to partition the work in a project based on objects.
7. The data-centered design approach enables us to capture more details of a model in
an implementable form.
8. Object-oriented systems can be easily upgraded from small to large systems.
9. Message passing techniques for communication between objects make the interface
descriptions with external systems much simpler.
10. Software complexity can be easily managed.
APPLICATIONS OF OOP
1. Real-time systems (eg. Air traffic control)
2. Simulation and modelling (eg. Weather forecasting)
3. Object oriented databases
4. Hypertext , hypermedia and expertext
5. AI and expert systems
6. Neural networks and parallel programming
7. Decision support (eg. GPS route planning) and office automation systems (eg.
MS office suite)
8. Computer Integrated Manufacturing (CIM) / Computer Aided Design (CAD) /
Computer Aided Manufacturing (CAM) System
❑ Java Virtual Machine (JVM):
• The Java Virtual Machine is called JVM, is an abstract computing machine or
virtual machine interface that drives the java code.
• JVM, i.e., Java Virtual Machine.
• JVM is the engine that drives the Java code.
• Mostly in other Programming Languages, compiler produce code for a particular
system, but Java compiler produce Bytecode for a Java Virtual Machine.
• When we compile a Java program, then bytecode is generated. Bytecode is the
source code that can be used to run on any platform.
• Bytecode is an intermediary language between Java source and the host system.
• It is the medium which compiles Java code to bytecode which gets interpreted on
a different machine and hence it makes it Platform/Operating system independent.
JVM’s work can be explained in following manner:
• Reading Bytecode.
• Verifying bytecode.
• Linking the code with the library.
DIAGRAM OF JVM:
• Java is called platform independent because of Java Virtual Machine. As different
computers with the different operating system have their JVM, when we submit
a .class file to any operating system, JVM interprets the bytecode into machine
level language.
• JVM is the main component of Java architecture, and it is the part of the JRE
(Java Runtime Environment).
• JVM is responsible for allocating the necessary memory needed by the Java
program.
• JVM is responsible for deallocating memory space.
❑Java Development Kit (JDK):
JDK (Java Development Kit) Includes a complete JRE (Java Runtime
Environment) plus tools for developing, debugging, and monitoring
Java applications. JDK is required to build and run Java applications
and applets.
❑Java Runtime Environment (JRE):
JRE stands for Java Runtime Environment, which provides an
environment at runtime. It is the cause of the implementation of JVM. It
contains a set of supporting libraries combined with core classes and
various other files that JVM uses at runtime. JRE is a part of JDK (Java
Development Toolkit) but can be downloaded separately.
❑ How JVM, JRE and JDK work together:
• Let’s first look at how the three core components of Java work together, and then
we can examine the differences. The diagram below provides an image of how
JVM, JRE and JDK fit together in the Java landscape.
• If you envision a baseball sliced open, it contains three main components: the
round cushioned core, the wool and cotton midsection and the cowhide exterior. A
ball without all three of these layers will not perform its intended function. Much
like the three basic parts of a baseball, JVM, JRE and JDK all have very specific
functions. Without all three, Java will not operate successfully.
Basic programming constructs:
1. Variables:
• A variable is an identifier that denotes a storage location used to store a data value.
• Unlike constants that remain unchanged during the execution of a program, a variable
may take different values at different times during the execution of the program.
• A variable name can be chosen by the programmer in a meaningful way so as to reflect
what it represents in the program.
• Some examples of variable names are: average, height, total_height, ClassStrength.
• Variable names may consist of alphabets, digits, the underscore( _ ) and dollar characters,
subject to the following conditions:
1. They must not begin with a digit.
2. Uppercase and lowercase are distinct. This means that the variable ‘Total’ is not the
same as total or TOTAL.
3. It should not be a keyword.
4. White space is not allowed.
5. Variable names can be of any length.
DECLARATION OF VARIABLES:
• After designing suitable variable names, we must declare them to the compiler.
• Declaration does three things:
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
3. A variable must be declared before it is used in the program.
• A variable can be used to store a value of any data type.
• The general form of declaration of a variable is
type variable1, variable2, ......, variableN;
• Variables are separated by commas.
• A declaration statement must end with a semicolon.
• Some valid declarations are:
int count;
float x, y;
double pi;
byte b;
char c1, c2, c3;
❑ Data types in Java:
Fig: Data types in Java
1. Integer Type
• Integer types can hold whole numbers such as 123, -96, and 5639.
• The size of the values that can be stored depends on the integer data type we choose.
• Java supports four types of integers. They are byte, short, int, and long.
• Table shows the memory size and range of all the four integer data types.
• It should be remembered that wider data types require more time for manipulation and
therefore it is advisable to use smaller data types, wherever possible.
• For example, instead of storing a number like 50 in an int type variable, we must use a
byte variable to handle this number. This will improve the speed of execution of the
program.
2) Floating Point Types
• Integer types can hold only whole numbers and therefore we use another type
known as floating point type to hold numbers containing fractional parts such as
27.59 and -1.375 (known as floating point constants).
• There are two kinds of floating point storage in Java. i.e. Float and Double.
• The float type values are single-precision numbers while the double types
represent double precision numbers.
• Table below gives the size and range of these two types.
• Floating point numbers are treated as double-precision quantities.
• To force them to be in single-precision mode, we must append for F to the
numbers.
• Example:1.23f7.56923e5F
• Double-precision types are used when we need greater precision in storage of
floating point numbers.
• All mathematical functions, such as sin, cos and sqrt return double type values.
3) Character Type:
• In order to store character constants in memory, Java provides a character data
type called char.
• The char type assumes a size of 2 bytes but, basically, it can hold only a single
character.
4) Boolean Type:
• Boolean type is used when we want to test a particular condition during the
execution of the program.
• There are only two values that a boolean type can take: true or false.
• Boolean type is denoted by the keyword boolean and uses only one bit of storage.
• All comparison operators return boolean type values.
• Boolean values are often used in selection and iteration statements.
• The words true and false cannot be used as identifiers.
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Shorthand assignment Operators
Shift Operators:
1) Left Shift Operator (<<):
• Left shift operator shifts the bits of the number towards left a specified
number of positions. The symbol for this operator is <<. When you
write x<<n, the meaning is to shift the bits of x towards left n
specified positions.
➢Example:
• If x=10, then calculate x<<2 value.
• Shifting the value of x towards the left two positions will make the leftmost
2 bits to be lost. The value of x is 10. The binary representation of 10
is 00001010. The procedure to do left shift explained in the following
example:
• Observe the above example, after shifting the bits to the left the binary
number 00001010 (in decimal 10) becomes 00101000 (in decimal 40).
2) Right Shift Operator:
• The Right Shift Operator shifts the bits of the number towards right a specified n
number of positions. Right shift operator represented by the symbol >>, read as
double greater than. When you write x>>n, the meaning is to shift the
bits x towards the right n specified positions.
• >> shifts the bits towards the right and also preserve the sign bit, which is the
leftmost bit. The leftmost bit represents the sign of the number. The sign
bit 0 represents a positive number, and 1 represents a negative number. So after
performing >> on a positive number, we get a positive value in the result also.
When we perform >> on a negative number, again we get a negative value.
➢Example:
• If x=10, then calculate x>>2 value.
• Shifting the value of x towards the right two positions will make the rightmost 2
bits to be lost. The value of x is 10. The binary representation of 10 is 00001010.
The procedure to do right shift explained in the following example:
• Observe the above example, after shifting the bits to the right the binary
number 00001010 (in decimal 10) becomes 00000010 (in decimal 2).
3) Shift Right with Zero Fill (>>>):
This operator shifts the first operand the specified number of bits to the
right. Excess bits shifted off to the right are discarded. Zero bits are
shifted in from the left. The sign bit becomes 0, so the result is always
non-negative. Unlike the other bitwise operators, zero-fill right shift
returns an unsigned 32-bit integer.
Consider the 32-bit binary representations of the decimal (base 10)
numbers 9 and -9:
Notice that the binary representation of the negative decimal (base 10)
number -9 is the two's complement of the binary representation of the
positive decimal (base 10) number 9. That is, it’s calculated by inverting
all the bits of 00000000000000000000000000001001 and adding 1.
In both cases, the sign of the binary number is given by its leftmost bit:
for the positive decimal number 9, the leftmost bit of the binary
representation is 0, and for the negative decimal number -9, the leftmost
bit of the binary representation is 1.
Given those binary representations of the decimal (base 10) numbers 9
and -9:
For the positive number 9, zero-fill right shift and sign-propagating right shift yield
the same result: 9>>>2 yields 2, the same as 9>>2:
Notice how two rightmost bits, 01, have been shifted off, and two zeroes have
been shifted in from the left. However, notice what happens for -9: -9>>2 (sign-
propagating right shift) yields -3, but -9>>>2 (zero-fill right shift) yields
1073741821:
Notice how two rightmost bits, 11, have been shifted off. For -9>>2 (sign-
propagating right shift), two copies of the leftmost 1 bit have been shifted in from
the left, which preserves the negative sign. On the other hand, for -9>>>2 (zero-fill
right shift), zeroes have instead been shifted in from the left, so the negative sign of
the number is not preserved, and the result is instead a (large) positive number.
INCREMENT AND DECREMENT OPERATORS
• Java has two very useful operators not generally found in many other
languages.
• These are the increment and decrement operators: ++ and --
• The operator ++ adds 1 to the operand while -- subtracts 1.
• Both are unary operators and are used in the following form:
++ m; or m ++;
-- m; or m --;
++ m; is equivalent to m = m + 1; (or m += 1;)
-- m; is equivalent to m = m - 1; (or m -= 1;)
• We use the increment and decrement operators extensively in for and while
loops.
• While ++m and m++ mean the same thing when they form statements independently, they
behave differently when they are used in expressions on the right-hand side of an
assignment statement.
• Consider the following:
m = 5;
y = ++m;
In this case, the value of y and m would be 6.
• Suppose, if we rewrite the above statement as:
m = 5;
y= m ++;
Then, the value of y would be 5 and m would be 6.
• A prefix operator first adds 1 to the operand and then the result is assigned to the variable
on left.
• On the other hand, a postfix operator first assigns the value to the variable on left and then
increments the operand.
Conditional Operators
• The character pair ? : is a ternary operator available in Java.
• This operator is used to construct conditional expressions of the form:
exp1 ? exp2 : exp3
where exp1, exp2, and exp3 are expressions.
• The operator ? : works as follows:
✓exp1 is evaluated first.
✓If it is non-zero (true), then the expression exp2 is evaluated and becomes the value of
the conditional expression.
✓If exp1 is false, exp3 is evaluated and its value becomes the value of the conditional
expression.
• Note that only one of the expressions (either exp2 or exp3) is evaluated.
• For example, consider the following statements:
a = 10;
b = 15;
x = (a > b) ? a : b;
• In this example, x will be assigned the value of b.
• This can be achieved using the if...else statement as follows:
if (a > b)
x = a;
else
x = b;
Expressions
• An expression in java is any valid combination of operators, constants and variables i.e.
Legal combination of tokens.
• The expression in java can be of any type:
Arithmetic/ Relational/ Logical/ Compound expression.