0% found this document useful (0 votes)
29 views57 pages

OOPS - Unit-1

The document provides an overview of Object-Oriented Programming (OOP) concepts through Java, detailing its features, history, data types, variables, and control structures. It explains key OOP principles such as classes, objects, abstraction, encapsulation, inheritance, and polymorphism, along with method overloading and constructors. The document serves as a foundational guide for understanding Java programming and its object-oriented paradigm.
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)
29 views57 pages

OOPS - Unit-1

The document provides an overview of Object-Oriented Programming (OOP) concepts through Java, detailing its features, history, data types, variables, and control structures. It explains key OOP principles such as classes, objects, abstraction, encapsulation, inheritance, and polymorphism, along with method overloading and constructors. The document serves as a foundational guide for understanding Java programming and its object-oriented paradigm.
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/ 57

Object Oriented Programming

through JAVA
UNIT - I
Java Buzzwords or Features of Java
• Simple
• Object-oriented
• Distributed
• Interpreted
• Robust
• Secure
• Architecture neutral
• Portable
• High performance
• Multithreaded
• Dynamic
History of Java
• James Gosling, often called as the father of Java
pioneered Java in June 1991 as a project called ‘Oak.
• In 1995, Java 1.0 was the first public execution - ‘Write
Once, Run Anywhere’ on popular platforms with free
runtimes.
• November 2006, Sun Microsystems launched a
considerable amount of Java in the General Public
License as free and open-source software.
• May 2007, Sun completed the process by releasing a
fully accessible, all-free, and open-source.
• In January 2010 oracle bought out by Sun Microsystems
Data Types
• Primitive data types -
 byte
 Short
 Int
 Long
 Float
 Double
 Boolean
 char
• Non-primitive data types –
 String
 Arrays
 Classes
Data Types
Variables
A variable is a name given to a memory location.
It is the basic unit of storage in a program.
• The value stored in a variable can be changed
during program execution.
• A variable is only a name given to a memory
location. All the operations done on the variable
affect that memory location.
• In Java, all variables must be declared before use.
Variables
Variable declaration
Syntax
Datatype var_name;
• datatype: Type of data
that can be stored in
this variable.
• var_name: Name given
to the variable.
Variables
Variable initialization Syntax
Datatype Var_name = value;
Variables
Types of variables
In Java, there are three types of variables:
Variables – Local Variable
A variable defined within a block or method or
constructor is called a local variable.
• These variables are created when the block is entered,
or the function is called and destroyed after exiting
from the block or when the call returns from the
function.
• The scope of these variables exists only within the
block in which the variables are declared, i.e., we can
access these variables only within that block.
• Initialization of the local variable is mandatory before
using it in the defined scope.
Variables – Instance Variable
Instance variables are non-static variables and are
declared in a class outside of any method, constructor,
or block.
• As instance variables are declared in a class, these
variables are created when an object of the class is
created and destroyed when the object is destroyed.
• Unlike local variables, we may use access specifiers for
instance variables. If we do not specify any access
specifier, then the default access specifier will be used.
• Initialization of an instance variable is not mandatory.
Its default value is 0.
• Instance variables can be accessed only by creating
objects.
Variables – Static Variable
(Class Variable)
Static variables are initialized only once, at the start of the
program execution. These variables should be initialized
first, before the initialization of any instance variables.
• These variables are declared similarly as instance variables.
The difference is that static variables are declared using the
static keyword within a class outside of any method,
constructor or block.
• Unlike instance variables, we can only have one copy of a
static variable per class, irrespective of how many objects
we create.
• Static variables are created at the start of program
execution and destroyed automatically when execution
ends.
• Initialization of a static variable is not mandatory. Its default
value is 0.
Variables
Differences between the Instance variables and the
Static variables
• Each object will have its own copy of an instance
variable, whereas we can only have one copy of a static
variable per class, irrespective of how many objects we
create.
• Changes made in an instance variable using one object
will not be reflected in other objects as each object has
its own copy of the instance variable. In the case of a
static variable, changes will be reflected in other
objects as static variables are common to all objects of
a class.
• We can access instance variables through only object
references, and static variables can be accessed directly
using the class name.
Variables
Scope of the variables
Arrays
Array in java is a group of like-typed variables
referred to by a common name.

Syntax:
Datatype[ ] var-name = new datatype[size];
Arrays
• In Java, all arrays are dynamically allocated.
• Arrays are stored in contiguous memory [consecutive
memory locations].
• Since arrays are objects in Java, we can find their length
using the object property length. This is different from
C/C++, where we find length using sizeof.
• A Java array variable can also be declared like other
variables with [] after the data type.
• The variables in the array are ordered, and each has an
index beginning with 0.
• Java array can also be used as a static field, a local
variable, or a method parameter.
• The size of the array cannot be altered (once initialized).
Jagged Arrays
A jagged array is an array of arrays such that member
arrays can be of different sizes, i.e., we can create a
2-D array but with a variable number of columns in
each row. These types of arrays are also known as
Jagged arrays.
Syntax:
data_type array_name[][] = new data_type[n][]; //n= no. of rows
array_name[] = new data_type[n1]; //n1= no. of columns in row-1
array_name[] = new data_type[n2]; //n2= no. of columns in row-2
array_name[] = new data_type[n3]; //n3= no. of columns in row-3
.
.
.
array_name[] = new data_type[nk]; //nk=no. of columns in row-n
Operators in Java
• Arithmetic Operators (+ , - , *, /, %)
• Unary Operators (++ , -- , ! )
• Assignment Operators ( = , += , -= , *= , /= , %= )
• Relational Operators ( == , < , <= , > , >= , != )
• Logical Operators ( && , ||)
• Ternary Operator (exp1 ? expr2 : exp3 )
• “instance of” operator
if statements
• Simple if statement
if (condition) {
//code
}
• Else statement
if (condition){
//code
}
else {
//code
}
if statements
• Else – if statement
if (condition1) {
//code
} else if (condition2) {
//code
} else {
//code
}
switch Statements
• Instead of writing many if..else statements, you
can use the switch statement.

switch(expression) {
case x: // code block
break;
case y: // code block
break;
default: // code block
}
while loop
• The while loop loops through a block of code
as long as a specified condition is true
Datatype loopcounterVar=val;
while (condition) {
// code block to be executed
}
do/while loop
• The do/while loop will execute the code block
once, before checking if the condition is true,
then it will repeat the loop as long as the
condition is true.
do {
// code block to be executed
} while (condition);
for loop
• When you know exactly how many times you
want to loop through a block of code, use
the for loop instead of a while loop.
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
• Statement 1 is executed (one time) before the
execution of the code block.
• Statement 2 defines the condition for executing
the code block.
• Statement 3 is executed (every time) after the
code block has been executed.
for-each loop
• A "for-each" loop, which is used exclusively to
loop through elements in an array
for (type variableName : arrayName) {
// code block to be executed
}
Type Casting
Type casting is when you assign a value of one
primitive data type to another type.
Types of casting:
1. Widening Casting (automatically) - converting a
smaller type to a larger type size
byte -> short -> char -> int -> long -> float -> double

2. Narrowing Casting (manually) - converting a larger


type to a smaller size type
double -> float -> long -> int -> char -> short -> byte
Object Oriented Paradigm
• Object oriented programming
paradigm allows decomposition
of the system into the number
of entities called objects and
then ties properties and
function to these objects.
• An object’s properties can be
accessed only by the functions
associated with that object but
functions of one object can
access the function of other
objects in the same cases using
access specifiers.
Object Oriented Paradigm
• Object-oriented programming paradigm
methods enable us to create a set of objects
that work together to produce software.
• The software produced using object-oriented
programming paradigm is easier to adapt to
the changing requirements, easier to
maintain, create modules of functionality.
Basic concepts Object Oriented
Programming
Basic concepts Object Oriented
Programming
Class
• A class is a user-defined blueprint or
prototype from which objects are created.
• It represents the set of properties or methods
that are common to all objects of one type.
• Using classes, you can create multiple objects
with the same behavior instead of writing
their code multiple times.
Basic concepts Object Oriented
Programming
Object
• An object is a basic unit of Object-Oriented
Programming that represents real-life entities.
• Any entity that has state and behavior is known
as an object. 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.
Basic concepts Object Oriented
Programming
Abstraction
• Data Abstraction is the property by virtue of which
only the essential details are displayed to the user.
Non-essential units are not displayed to the user.
• Hiding internal details and showing functionality is
known as abstraction.
• In Java, abstraction is achieved
by interfaces and abstract classes. We can achieve
100% abstraction using interfaces.
Example: Phone call, we don't know the internal
processing.
Basic concepts Object Oriented
Programming
Encapsulation
• An Encapsulation is the process of wrapping up
data and functionalities into a single unit.
Example: Classes (a capsule, it is wrapped with
different medicines)
• In encapsulation, the data in a class is hidden
from other classes, which is similar to what data-
hiding does. So, the terms “encapsulation” and
“data-hiding” are used interchangeably.
Basic concepts Object Oriented
Programming
Inheritance
• When one object acquires all the
properties and behaviors of a parent
object, it is known as inheritance. It
provides code reusability.
• Inheritance is the property whereby
one class extends another class
properties, including methods and
variables.
• The original class is called a
superclass, and the class that
exceeds the properties are called a
subclass. As the subclass contains all
the data of the superclass, it is more
specific.
Basic concepts Object Oriented
Programming
Polymorphism:
Polymorphism means the
ability to take more than
one form. An operation may
exhibit different behavior in
a different instance.
• Behavior depends on the
types of data used for the
operation.
Example: A Vehicle – it can
be in many forms like 2
wheeler, 3 wheeler, 4
wheeler.
Concept of Classes
Class is a set of object which shares common
characteristics/ behavior and common properties/
attributes.
• Class is not a real world entity. It is just a template or
blueprint or prototype from which objects are created.
• Class does not occupy memory.
• Class is a group of variables of different data types and
group of methods.
• A class in java can contain data members, methods,
constructor, nested classes and interfaces
Concept of Classes
Class is a set of object which Syntax to declare a class:
shares common characteristics/ access_modifier
behavior and common class<class_name>
properties/ attributes. {
• Class is not a real world entity. It data member;
is just a template or blueprint or
prototype from which objects method;
are created. constructor;
• Class does not occupy memory. nested class;
• Class is a group of variables of interface;
different data types and group of }
methods.
• A class in java can contain data
members, methods, constructor,
nested classes and interfaces
Concept of Objects
• It is a basic unit of Object-Oriented Programming and represents
real-life entities. A typical Java program creates many objects, which
as you know, interact by invoking methods. An object consists of :
• State: It is represented by attributes of an object. It also reflects the
properties of an object.
• Behavior: It is represented by the methods of an object. It also
reflects the response of an object with other objects.
• Identity: It gives a unique name to an object and enables one
object to interact with other objects
• Example of an object: dog
Method Overloading
• Method Overloading allows different methods to
have the same name, but different signatures
where the signature can differ by the number of
input parameters or type of input parameters, or
a mixture of both.
• Method overloading is also known as Compile-
time Polymorphism, Static Polymorphism in Java.
In Method overloading compared to parent
argument, child argument will get the highest
priority.
Method Overloading
Different Ways of Method Overloading in Java
• Changing the Number of Parameters.
• Changing Data Types of the Arguments.
• Changing the Order of the Parameters of
Methods
Constructors
• A constructor in Java is a special method that is used
to initialize objects.
• The constructor is called when an object of a class is
created.
• It is called when an instance of the class is created.
• At the time of calling the constructor, memory for the
object is allocated in the memory.
• It is a special type of method which is used to
initialize the object.
Constructors
How Constructors are Different from Methods in Java?
• Constructors must have the same name as the class
within which it is defined it is not necessary for the
method in Java.
• Constructors do not return any type while method(s)
have the return type or void if does not return any
value.
• Constructors are called only once at the time of
Object creation while method(s) can be called any
number of times.
Constructors
Syntax
class Person
{
.......
// A Constructor
Person()
{
}
.......
}
Constructors
Types of Constructors
1. No argument constructor
2. Parameteritized constructor
3. Default constructor
Constructors – No argument
Constructor
1. No argument constructor:
A constructor that has no parameter is known as
the No-argument or Zero argument constructor. If
we don’t define a constructor in a class, then the
compiler creates a constructor(with no
arguments) for the class.
Constructors – Parameterized
Constructor
2. Parameterized constructor:
A constructor that has parameters is known as
parameterized constructor. If we want to initialize
fields of the class with our own values, then use a
parameterized constructor.
Constructors – Default Constructor
3. Default constructor:
If we do not create any constructor, the Java
compiler automatically create a no-argument
constructor during the execution of the program.
This constructor is called default constructor.
Constructors – Overloading
• We can overload constructors for creating objects
in different ways.
• The compiler differentiates constructors on the
basis of the number of parameters, types of
parameters, and order of the parameters.
Important Notes on Java Constructors
• Constructors are invoked implicitly when you instantiate objects.
• The two rules for creating a constructor are:
The name of the constructor should be the same as the class.
A Java constructor must not have a return type.
• If a class doesn't have a constructor, the Java compiler automatically
creates a default constructor during run-time. The default constructor
initializes instance variables with default values. For example,
the int variable will be initialized to 0
• Constructor types:
No-Arg Constructor - a constructor that does not accept any arguments
Parameterized constructor - a constructor that accepts arguments
Default Constructor - a constructor that is automatically created by the
Java compiler if it is not explicitly defined.
• A constructor cannot be abstract or static or final.
• A constructor can be overloaded but can not be overridden.
this keyword
• ‘this’ is a reference variable that refers to the
current object.
Following are the ways to use ‘this’ keyword in java
:
1. Using ‘this’ keyword to refer current class
instance variables
2. Using this() to invoke current class constructor
3. Using ‘this’ keyword to invoke current class
method
Parameter Passing
• Pass By Value: Changes made to formal
parameter do not get transmitted back to the
caller. Any modifications to the formal
parameter variable inside the called function
or method affect only the separate storage
location and will not be reflected in the actual
parameter in the calling environment. This
method is also called as call by value.
Parameter Passing
• Call by object: Changes made to formal
parameter do get transmitted back to the
caller through parameter passing. Any
changes to the formal parameter are reflected
in the actual parameter in the calling
environment as formal parameter receives a
reference (object) to the actual data. This
method is also called as call by object. This
method is efficient in both time and space.
Garbage collection
• In java, garbage means unreferenced objects.
• Garbage Collection is process of reclaiming the runtime
unused memory automatically. In other words, it is a
way to destroy the unused objects.

Advantage of Garbage Collection


• It makes java memory efficient because garbage
collector removes the unreferenced objects from heap
memory.
• It is automatically done by the garbage collector(a part
of JVM) so we don't need to make extra efforts.
Nested Classes
• A class defined within Syntax:
another class, such class OuterClass
classes are known {
as nested classes. They
enable you to logically ...
group classes that are class NestedClass
only used in one place, {
thus this increases the ...
use of encapsulation, and }
creates more readable
}
and maintainable code.
Nested Classes

Static nested class : Nested classes that are


declared static are called static nested classes.
Inner class : An inner class is a non-static nested class.
Nested Classes
• In the case of inner classes, without an outer class object existing,
there cannot be an inner class object. i.e., an object of the inner class
is always strongly associated with an outer class object.
• To create an object for the inner class, use this syntax:
OuterClass outerObject = new OuterClass();
OuterClass.InnerClass innerObject = outerObject.new
InnerClass();

• But in the case of static nested class, Without an outer class object
existing, there may be a static nested class object. i.e., an object of a
static nested class is not strongly associated with the outer class
object.
• To create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject = new
OuterClass.StaticNestedClass();
Object Class
• Object class is present
in java.lang package. Every
class in Java is directly or
indirectly derived from
the Object class.
• If a class does not extend
any other class then it is a
direct child class
of Object and if extends
another class then it is
indirectly derived.

You might also like