0% found this document useful (0 votes)
8 views

Unit 1 OOP Elements

Uploaded by

right2abhinavrs
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)
8 views

Unit 1 OOP Elements

Uploaded by

right2abhinavrs
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/ 62

23CSE111 OBJECT ORIENTED

PROGRAMMING

Dr. M. ANBAZHAGAN
Unit 1
Structured to Object Oriented Approach by Examples - Object Oriented
languages - Properties of Object Oriented system – UML and Object-
Oriented Software Development - Use case diagrams and documents
as a functional model – Identifying Objects and classes -
Representation of Objects and its state by Object Diagram - Simple
Class using class diagram – Encapsulation - Data Hiding - Reading and
Writing Objects - Class Level and Instance Level Attributes and
Methods- JIVE environment for debugging.
OOP
Fundamentals
What is OOP?
Object-Oriented Programming is a programming paradigm that organizes
software design around objects, which are instances of classes. Objects
encapsulate data (attributes) and behavior (methods) into a single entity,
allowing for modular, reusable, and scalable code.
What is Object?
An object is a fundamental unit in Object-Oriented Programming that
represents a specific instance of a class, containing both data (attributes) and
behavior (methods). Objects are used to model real-world entities or
concepts in a structured and reusable way.
What is Class?
A class is a blueprint or template used to define the structure and behavior of
objects in Object-Oriented Programming (OOP). It specifies the attributes
(data) and methods (functions) that objects created from the class will have.
Structured to Object-oriented
• The evolution from structured to object-oriented programming represents
a significant shift in software development paradigms

• Focuses on a top-down approach, • Adopts a bottom-up approach,


breaking tasks into smaller, organizing code into objects that
manageable sub-tasks using functions encapsulate data and behaviors
or procedures • It introduces concepts such as classes,
• It emphasizes linear flow and uses inheritance, polymorphism, and
control structures like loops and encapsulation, promoting code reuse
conditionals to process data and modularity
What does this paradigm shift allow?
The paradigm shift from SP/PP to OOP allows programmers to
model real-world entities and their interactions, making the
development process more intuitive
Structured Vs. Object-oriented
Main Function Object n

Bottom-up Approach
Top-down Approach

Subfunction 1

Object 2
Subfunction 2

Object 1

Subfunction n Class
Top-down Vs. Bottom-up w.r.t Problem
Solving
Structured to Object-oriented

Edsger W. Dijkstra Alan Kay


Structured Vs. Object-oriented
Aspect Structured Object-oriented
A collection of variables grouped A paradigm that organizes data and
Definition
together under one name behavior into objects
Data-centric: Focuses on grouping Object-centric: Focuses on objects
Focus
related data containing both data and behavior
Does not inherently support Strongly supports encapsulation via
Encapsulation
encapsulation classes
Functions are defined separately
Methods Methods are part of objects
from structures
Access Supports access control (private, public,
Lacks access control
Modifiers protected)
Supports abstraction through abstract
Abstraction Limited or no abstraction features
classes and interfaces
Useful for lightweight data Suitable for building complex and
Usage Context
modelling scalable systems
Structured Vs. Object-oriented
#include <stdio.h> // Define a class for Student
#include <string.h> class Student {
private String name;
// Define a structure for Student private int rollNumber;
struct Student { No private float marks;
char name[50]; encapsulation
int rollNumber; // Constructor to initialize Student object
of data and
float marks; public Student(String name, int rollNumber, float marks) {
operation this.name = name;
}; Encapsulation
this.rollNumber = rollNumber;
of data and
// Function to display Student details this.marks = marks;
} operation
void displayStudent(struct Student s) {
printf("Name: %s\n", s.name);
printf("Roll Number: %d\n", s.rollNumber); // Method to display Student details
printf("Marks: %.2f\n", s.marks); public void displayStudent() {
} System.out.println("Name: " + name);
System.out.println("Roll Number: " + rollNumber);
int main() { System.out.println("Marks: " + marks);
// Declare and initialize a Student structure }
struct Student student1; }
strcpy(student1.name, "John Doe");
student1.rollNumber = 101; public class Main {
student1.marks = 85.5; public static void main(String[] args) {
// Create and initialize a Student object
Student student1 = new Student("John Doe", 101, 85.5f); Object Creation
// Display student details using a function
printf("Student Details:\n");
displayStudent(student1); // Display student details using a method
System.out.println("Student Details:");
return 0; student1.displayStudent();
} }
}
Structured Vs. Object-oriented
Uninitialized Variables

In structured programming (e.g., C),


OOP often mitigates this issue through
uninitialized variables are a common
constructors, which initialize class fields
source of bugs
upon object creation
If a variable is not explicitly initialized, it class Student {
contains garbage values, leading to int age; // Default initialization to 0 public
undefined behavior
Student(int age) {
int x; this.age = age; // Explicit initialization
printf("%d\n", x); }
}
Structured Vs. Object-oriented
Resource Deallocation

OOP relies on destructors (e.g., C++) or


In SP, memory allocation (e.g., malloc() in
garbage collection (e.g., Java, Python) to
C) requires manual deallocation using
handle resource deallocation, significantly
functions like free()
reducing manual intervention and risks of
memory leaks
Forgetting to free memory leads to
memory leaks, while double freeing
class Resource {
causes undefined behavior. @Override
protected void finalize() throws Throwable {
int* ptr = (int*)malloc(sizeof(int)); System.out.println("Object is garbage
// Programmer must explicitly free the memory collected.");
free(ptr); }
}
Structured Vs. Object-oriented
Abstraction

SP often lacks abstraction, leading to


repetitive code and tight coupling OOP supports abstraction through abstract
classes, interfaces, and polymorphism,
Functions are written to perform specific enabling flexible and reusable designs
tasks, but there's no direct support for
abstracting common behavior across abstract class Shape {
different entities abstract void draw();
}
// Repetition for different data types
class Circle extends Shape {
void printInt(int x) {
@Override
printf("%d\n", x); }
void draw() {
System.out.println("Drawing Circle"); }
void printFloat(float x) {
}
printf("%f\n", x); }
Java
Fundamentals
Java’s Portability
“Write once, run anywhere!”
How does Java achieve portability?
• Java compiles source code into an intermediate form called bytecode
• The bytecode is stored in files with a “.class” extension, and it is a platform-
independent representation of the Java program
Java is a Compiled and Interpreted
Language
Source/Byte/Object Codes
• Source Code
• Source code is the human-readable form of a program that developers write
• A snippet of code that is written using Java syntax and can be understood by
programmers
• Source code is the foundation of any software development process and
serves as the starting point for creating a program
Source/Byte/Object Codes
• Object/Machine Code
• The binary format that computers can understand
• It consists of zeros and ones, which represent the instructions that a
computer’s central processing unit (CPU) can execute
• Machine code is specific to a particular computer architecture and processor
model
Source/Byte/Object Codes
• Byte Code
• Java bytecode is an intermediate representation of a Java program, generated
after the compilation of the Java source code (.java files)
• This bytecode is stored in .class files and can be executed by the Java Virtual
Machine (JVM)
How does the Java code become portable?

Source Code Java Compiler Byte Code


(.java) (javac) (.class)

Java Virtual Machine (JVM)

Native Java Runtime Byte Code


Class Loader
Operating System Environment Verifier
Java Ecosystem: JDK, JRE, & JVM
JDK
JRE

Development Class
Tools JVM Libraries
Java Development Kit (JDK)
• The all-in-one toolkit for Java developers
• It's the outermost layer in the ecosystem and contains everything needed
to develop, compile, debug, and run Java applications
• What Does the JDK Include?

Development Tools
The JDK comes with essential tools Java Runtime Environment (JRE)
such as the Java compiler (javac), the The JDK contains the JRE, allowing
debugger, and utilities that developers developers to run the code they write,
rely on to write and troubleshoot their all within the same environment
Java code
Java Runtime Environment (JRE)
• JRE is nested inside the JDK and represents the environment required to run
Java applications
• It's like the engine of a car that makes everything move once the pieces are in
place
• The JRE is perfect for those who don't need to develop Java programs but need to
run them

Java Virtual Machine (JVM)


The JRE contains the JVM, the core Class Libraries
engine responsible for executing Java The JRE also includes class libraries,
bytecode and converting it into which are a set of reusable code that
machine-level instructions that your developers can utilize
system can understand
Java Virtual Machine (JVM)
• The JVM is an abstract computing machine that enables a computer to run
Java programs and other languages compiled to Java bytecode
• This abstraction allows Java to run on different platforms without needing
any changes — whether it's a Windows PC, a Mac, or a Linux server
• The JVM also provides important services like memory management and
garbage collection, making sure that Java applications run smoothly and
efficiently
• JVM’s key components:

Runtime Data Java Native Native Method


Class Loader Execution Engine
Areas Interface (JNI) Libraries
JVM Architecture
Java Virtual Machine

Class Loader

Native
Class Area Heap Stack PC Register Method
Stack

Native Method Java Native


Execution Engine
Interface Libraries
Java Vs. Python
Performance

Aspect Java Python

Slower due to dynamic typing and


Speed Faster due to static typing and JIT
interpreted execution.
Interpreted; no compilation to
Compilation Compiles to bytecode; runs on JVM
bytecode

Execution Optimized with JIT Compiler Runs line by line, which is slower
Java Vs. Python
Typing System

Aspect Java Python

Typing Statically typed (types declared) Dynamically typed (types inferred)

Flexibility Less flexible; requires explicit types More flexible due to implicit typing

Error Detection Errors caught at compile-time Errors often caught at runtime


Java Vs. Python
Typing System

Aspect Java Python

Simple, concise, and readable


Syntax Verbose with strict syntax rules
syntax
public class Hello {
public static void main(String[] args) {
Example System.out.println("Hello World"); print("Hello World")
}
}
Java Vs. Python
Memory Management

Aspect Java Python

Garbage
Automatic Garbage Collection (JVM) Automatic Garbage Collection
Collection

Memory Usage More efficient for large applications Higher memory consumption
Java Vs. Python
Portability

Aspect Java Python

Platform Portable but depends on Python


"Write Once, Run Anywhere" (JVM)
Independence interpreter
Runs on any system with Python
Execution Requires JVM to run on any platform
installed
Java Vs. Python
Community and Ecosystem

Aspect Java Python

Strong support for enterprise Strong support for AI, ML, and
Community
software scripting
Robust libraries for enterprise and Extensive libraries for data science,
Libraries
web ML, and automation
Java Vs. Python
• Java: Best suited for large-scale enterprise applications, Android
development, and applications requiring high performance and strict
typesafety
• Python: Preferred for data science, machine learning, AI, scripting, and
applications requiring faster development with simple syntax
OOP
Elements
Elements of OOP Model

Major Elements
Minor Elements
Abstraction
Strong Typing
Encapsulation
Concurrency
Inheritance

Modularity Persistence
Abstraction
Abstraction is a core principle of Object-Oriented Programming that focuses
on hiding implementation details and exposing only the essential features or
functionality of an object
Key Features of Abstraction
• Hiding Complexity
• Abstraction hides the "how" (implementation) and shows only the "what"
(functionality)
• For example, when you drive a car, you use the steering wheel to turn, but
you don’t need to understand how the steering mechanism works internally
• Essential Information Only
• It provides only the details necessary for the user and omits the unnecessary
ones
• Example: A List in Python or Java provides methods like add() and remove(),
but hides how the elements are stored internally
Types of Abstraction
Process/Control Elements
Data Abstraction
Hides the implementation details
Hides internal details about how
of control flow and provides a
data is stored or represented
simple interface to perform
E.g. A databases
complex operations
E.g. A sort function
Abstraction in OOP
Abstract Classes Interfaces
• An abstract class is a class that • An interface defines a contract or
cannot be instantiated directly blueprint for a class, specifying
and is meant to be subclassed what methods it should
• It may contain abstract methods implement

abstract class Shape { interface Vehicle {


abstract void draw(); // Abstract method void start();
} }

class Circle extends Shape { class Car implements Vehicle {


void draw() { public void start() {
System.out.println("Drawing Circle"); System.out.println("Car is starting");
} }
} }
Examples of Abstraction in Real Life
Encapsulation
Encapsulation is one of the fundamental principles of OOP that refers
to bundling data (attributes) and methods (functions) that operate on
the data into a single unit, usually a class
Key Features of Encapsulation
Improved
Control Access
Data Hiding Maintainability
Provides controlled access
Encapsulation allows
Encapsulation hides the to an object's data through
changes to the internal
internal state of the object public methods (like getters
implementation of a class
and prevents unauthorized and setters), ensuring that
without affecting its
access changes to the data are
external behavior or
valid
dependent code
Encapsulation in Java
class Employee {
private String name; // Private field
private int age;

// Getter for name


public String getName() {
return name;
}

// Setter for name public class Main {


public void setName(String name) { public static void main(String[] args) {
this.name = name; Employee emp = new Employee();
} emp.setName("Alice");
emp.setAge(25);
// Getter for age
public int getAge() { System.out.println("Name: " + emp.getName());
return age; System.out.println("Age: " + emp.getAge());
} }
}
// Setter for age
public void setAge(int age) {
if (age > 0) { // Validation
this.age = age;
} else {
System.out.println("Invalid age");
}
}
}
Real-World Example of
Encapsulation

Bank Account
Balance You cannot directly change the
account balance; you must use
Deposit() controlled methods like deposit() or
Withdraw() withdraw()…!
Check_balance()
Abstraction Vs. Encapsulation
Abstraction is the process of Encapsulation is the process of
hiding the implementation bundling data and methods
details and showing only together and restricting direct
essential features access to data
Focuses on how the data and
Focuses on what an object does
methods are secured and
Abstract classes, interfaces, or organized
high-level method definitions Private fields, getters, setters,
Simplifies the complexity of a and access modifiers
system and provides a clear Ensures the integrity and security
interface of the data within an object
Inheritance
Inheritance is a fundamental principle of OOP that allows a class
(called the child class or subclass) to acquire the properties and
behaviors (methods) of another class (called the parent class or
superclass)
Class Hierarchy (is-a relationship)
• JAVA accomplishes inheritance by arranging all of its classes in a "family-
tree”- like ordering called a class hierarchy
• A class hierarchy is often represented as an upside down tree
• The more “general” kinds of objects are higher up the tree and the more
“specific” kinds of objects are below them in the hierarchy
Key Features of Inheritance

Code Reusability Extensibility


Common attributes and methods Subclasses can extend the functionality
defined in a parent class can be reused of the parent class by adding new
in multiple child classes methods or overriding existing ones

Hierarchy Polymorphism
Inheritance establishes a hierarchical With inheritance, subclasses can
relationship between classes, where override methods of the parent class,
subclasses derive from a base class enabling polymorphism
Types of Inheritance
Multiple Inheritance – A Glance
A child class inherits from multiple parent classes - This can lead to the
diamond problem
Modularity
• Modularity refers to the design principle of
breaking down a program into smaller,
manageable, and self-contained units or
modules
• Each module is designed to perform a
specific task and can be developed, tested,
and maintained independently
• Modularity makes complex systems easier
to understand, develop, and maintain
How to Achieve Modularity?

Classes

Modularity Packages

Modules
Minor Elements of OOP
Strong Typing Concurrency Persistence
This means that the type of Concurrency refers to the Persistence refers to the
a variable is known at ability of a program to characteristic of an object
compile time and once a execute multiple parts of a to continue to exist even
variable is declared to be of task simultaneously after the program that
a certain type, it cannot created it has ended
hold values of other types
Object Serialization in Java
• in Java is the process of converting an object's state into a byte stream,
which can then be stored in a file, sent over a network, or transferred
between different Java Virtual Machines

Saved in a File

Serialization
Object Bytes Sent over a Network

Platform Transferred b/w


Independent JVMs
Object Deserialization
• Deserialization is the process of converting a byte stream back into a copy
of the original object, essentially reversing the serialization process

From a File

Deserialization
From a Network Bytes Object

From a JVM
How to Serialize and Deserialize?
• Serializable Interface:
• An object can be serialized by implementing the Serializable interface

public class MyClass implements Serializable {


private static final long serialVersionUID = 1L;
private String name;
private int age;

// Constructor, getters, setters, etc.


}
How to Serialize and Deserialize?
• Writing Object to a File:
• To serialize an object, you can use ObjectOutputStream to write the
object to a file or any other output stream
MyClass obj = new MyClass("Alice", 30);

try (FileOutputStream fileOut = new FileOutputStream("myclass.ser");


ObjectOutputStream out = new ObjectOutputStream(fileOut)) {
out.writeObject(obj);
}
catch (IOException e) {
e.printStackTrace();
}
How to Serialize and Deserialize?
• Reading Object from a File:
• To deserialize an object, you can use ObjectInputStream to read the
object from a file or any other input stream
MyClass obj = null;

try (FileInputStream fileIn = new FileInputStream("myclass.ser");


ObjectInputStream in = new ObjectInputStream(fileIn)) {
obj = (MyClass) in.readObject();
}
catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
Classroom Activity 1
Identify all possible attributes and methods for the following real-
world objects and write your Java class for them.

You might also like