JAVA-OOPs
JAVA-OOPs
UNIT – I
As of August 2024, Java 22 is the latest released Java version. In September 2024,
Java 23 will follow.
Java Editions - Java is available in several editions, each tailored for different types of
applications:
4. JavaFX
o Purpose: Provides a platform for building rich desktop applications with advanced
graphical user interfaces and multimedia capabilities.
o Key Features: Includes APIs for creating modern UIs, handling graphics, and
integrating multimedia into Java applications. Application programming
interfaces
Travel Booking
Travel Itinerary (API Documentation): The travel booking system provides endpoints for
booking flights, hotels, and car rentals. It includes details on how to specify travel dates,
destinations, and preferences.
Placing a Booking Request (API Request): You want to book a flight from New York to Paris.
You submit a request specifying your travel dates and preferences.
Processing the Booking (API Processing): The booking system (server) checks availability,
processes your request, and reserves a flight based on your input.
1
Receiving Your Booking Confirmation (API Response): The booking system sends you a
confirmation with your flight details, such as the flight number, departure time, and booking
reference.
1. Sequence:
Step 1: Gather ingredients.
Step 2: Preheat the oven.
Step 3: Mix ingredients.
Step 4: Pour the batter into the pan.
2. Selection:
If the oven is preheated, then place the pan inside.
If the cake is golden brown, then remove it from the oven.
3. Iteration:
Stir the batter continuously for 5 minutes.
Check every 5 minutes if the cake is done until it passes the toothpick test.
4. Modularity:
You could have separate functions for gatherIngredients(), mixIngredients(),
bakeCake(), each handling a part of the process.
Structured Programming is often preferred for simpler, more linear tasks, while OOP is
better suited for complex, large-scale systems that require modularity, reusability, and a closer
representation of real-world entities.
2
Structured programming languages are designed to support the structured programming
paradigm, which emphasizes clear, logical control flow through the use of sequences, selections,
and iterations. Here are some examples of structured programming languages:
1. C
2. Pascal
Description: Pascal was designed as a teaching tool for structured programming and
data structuring. It emphasizes readability and clean code structure.
Use Cases: Education, academic research, early software development, and desktop
applications.
4. Ada
Description: BASIC was originally a simple language for beginners, but structured
variants like QBASIC and Visual Basic introduced structured programming features.
Use Cases: Education, small-scale application development, and rapid prototyping.
6. ALGOL
3
7. Modula-2
8. PL/I
9. Turing
Summary
4
Object-Oriented Programming (OOP) is a programming paradigm that models software
design around objects, which are instances of classes. These objects represent real-world entities
and concepts, encapsulating data (attributes) and behaviors (methods) together in a single unit.
Analogy: Imagine you're a chef who creates a recipe (Java source code). Your recipe
needs to be followed in different automated kitchens around the world (platforms), each
with its own cooking appliances. You write the recipe in your language, but since each
kitchen only understands its own specific set of instructions, you use a translator (Java
compiler) to convert your recipe into a universal set of commands (bytecode) that any
automated kitchen can understand. No matter the location or appliances, the dish will turn
out exactly as you intended.
Analogy: You write a novel (Java source code) that you want to be read worldwide.
However, people in different countries speak different languages (platforms). So, you hire
translators (Java compiler) to convert your novel into various languages (bytecode). This
way, readers (JVM) in any country can enjoy your story exactly as you wrote it, without
needing you to rewrite it in each language.
Analogy: You’re a teacher who creates lesson plans (Java source code) for students in
different schools (platforms). Each school has its own teaching methods and materials. To
ensure all students learn the same material, you create a universal lesson plan guide
(bytecode). The schools (JVMs) then use this guide to teach the lesson in their own way,
ensuring consistency in education.
Analogy: You’re a fashion designer who creates a new clothing line (Java source code).
This clothing needs to be produced in factories (JVMs) around the world, each with
different fabrics and sewing techniques (platforms). You create a detailed pattern and
instruction manual (bytecode) that can be used by any factory. This ensures that the
clothing is made to your specifications, no matter where it’s produced.
You browse various products, such as electronics and clothing. Each product you view is
an instance of the Product class, displaying details like price, description, and stock
availability.
You decide to buy a smartphone (an instance of the Electronics subclass) and a t-shirt (an
instance of the Clothing subclass). When you add them to your cart, the system uses the
ShoppingCart class to manage these items.
At checkout, you choose to pay with PayPal. The Order class handles your purchase,
interacting with the PayPalPayment subclass to process the payment.
Your order is placed, and you can track it using the trackOrder() method in the Order
class.
5
In this example, the OOP principles work together to create a system where different types of
products, customers, and payment methods interact seamlessly, providing a robust and scalable
online shopping experience.
A class in Java is a blueprint or template that defines the properties (attributes) and behaviors
(methods) that objects created from the class will have. It doesn't represent any actual data, but
it serves as a model from which objects are created.
An object is an instance of a class. It is a tangible entity that has a state (defined by its
attributes) and behavior (defined by its methods). When you create an object from a class, you
are bringing that blueprint to life, assigning actual data to the attributes, and using the methods
to perform actions.
Real-Time Examples
Class: Car
o Attributes: make, model, year, color, engineSize
o Methods: startEngine(), accelerate(), brake(), paint()
Explanation:
The Car class is a blueprint that defines what properties a car should have (like make,
model, and year) and what actions it can perform (like startEngine() or accelerate()).
Object: Imagine you want to create an actual car—a specific car, say, a 2022 red Tesla
Model S with a 100 kWh battery. In Java, this specific car is an object created from the Car
class:
Here, myCar is an object of the Car class. It has specific values for its attributes (like Tesla
for make and Red for color) and can use the methods defined in the Car class.
Class: Product
o Attributes: productID, name, price, stockQuantity
o Methods: displayDetails(), applyDiscount(), updateStock()
Explanation:
The Product class is a general template for any product that can be sold in an online store.
It defines the common properties like productID, name, and price, and methods that can
be applied to any product, like applyDiscount().
Object:
6
Let's say you are managing an online store and want to add a specific product, like a
"Laptop":
Here, laptop is an object of the Product class, representing a specific item with a productID
of 101, a name of "Laptop", a price of $1200.00, and a stockQuantity of 50.
Class: Student
o Attributes: studentID, name, age, grade, courses
o Methods: enrollCourse(), dropCourse(), viewGrades()
Explanation:
The Student class represents the concept of a student, with attributes like studentID,
name, and grade, and methods that define what actions a student can perform, like
enrolling in or dropping courses.
Object:
If the school system needs to manage a particular student, say, John Doe who is 16 years
old and in 10th grade:
Here, student1 is an object of the Student class, representing a specific student with
unique data.
Summary
Class: The blueprint or template that defines the attributes (data) and methods
(behaviors) common to all objects of that type. It's like the design of a house—many
houses can be built from the same design.
Object: An instance of a class with specific values assigned to its attributes. It's like an
actual house built from a design, with specific colors, materials, and layout.
In Java, classes define what an object will look like and what it can do, while objects are the
actual entities that you work with in your program.
7
1. Classes and Objects:
o Class: Product
Attributes: productID, name, price, stockQuantity
Methods: displayDetails(), updateStock()
o Class: Customer
Attributes: customerID, name, email, cart
Methods: addToCart(), checkout()
o Class: Order
Attributes: orderID, customer, productList, totalAmount
Methods: placeOrder(), cancelOrder()
2. Encapsulation:
o The Product class encapsulates all the information about a product, like its ID,
name, price, and stock quantity. Only certain methods allow interaction with these
attributes, protecting the data.
3. Abstraction:
o Customers on the platform interact with a simple interface. For example, they can
click a button to addToCart() or checkout(). They don't need to know how the cart
manages inventory or processes payments—the complexity is abstracted away.
4. Inheritance:
o You could have different types of customers, such as RegularCustomer and
PremiumCustomer. Both might inherit common attributes and methods from the
Customer class, but PremiumCustomer might have additional discounts or benefits.
5. Polymorphism:
o During the checkout process, the platform might use different payment methods
(credit card, PayPal, etc.). The system processes the payment by calling a
processPayment() method. Depending on the payment type object, the payment
will be processed differently.
1. Encapsulation
2. Abstraction
3. Inheritance
4. Polymorphism
8
1. Encapsulation
Advantage: Encapsulation allows you to bundle data (attributes) and methods (functions) that
operate on the data into a single unit, or object. This helps in hiding the internal state of the
object from the outside world and only exposing what is necessary.
Real-Life Example: Consider a TV remote control. The user interacts with the remote through
buttons (e.g., power on/off, volume up/down) but doesn't need to understand the intricate
electronics inside the remote. The internal workings are encapsulated within the remote, while
the user interface is simple and easy to use.
Explanation: Encapsulation in OOP helps in protecting the internal state of an object and allows
for controlled access through public methods. This leads to improved security and maintenance
of the code.
2. Abstraction
Abstraction simplifies complex systems by hiding the implementation details and exposing only
the necessary parts. It allows you to interact with objects through a simple interface, without
needing to understand the intricate workings underneath.
Class: ATM
Methods: withdrawCash(), checkBalance(), depositCash()
When you use an ATM, you don't need to understand how it communicates with the bank's
servers, how it verifies your PIN, or how it dispenses cash. You interact with the ATM through a
simple interface, where you select options like withdrawCash() or checkBalance(). The complex
processes behind the scenes are abstracted away.
3. Inheritance
Inheritance is a mechanism where a new class (child class) inherits attributes and methods
from an existing class (parent class). This allows for code reusability and the creation of a
hierarchical relationship between classes.
9
Child Class: Motorcycle (inherits from Vehicle)
o Additional Attributes: handlebarType
o Methods: Inherits start() and stop(), adds kickstand()
In this example, both Car and Motorcycle inherit the basic attributes and behaviors of a Vehicle.
They can also have additional attributes and methods that are specific to their type. This allows
you to create specialized vehicle types without duplicating code.
4. Polymorphism
Polymorphism allows objects to be treated as instances of their parent class, but each object
can also behave differently based on its class. It enables a single interface to work with different
underlying forms (data types or classes).
In this example, a processPayment() method can be called on any object that is a subclass of
Payment. Depending on whether the object is an instance of CreditCardPayment or
PayPalPayment, the payment will be processed differently. This is polymorphism—different
behaviors based on the object type, using a single interface.
Summary
1. Programming Paradigm
Structured Programming:
o Focuses on the logical structure and flow of the program. The program is divided
into small functions or procedures that are called when needed.
o Examples: C, Pascal, Fortran
Object-Oriented Programming (OOP):
o Focuses on modeling the program using objects that represent real-world entities.
The program is divided into classes and objects that encapsulate both data and
behavior.
o Examples: Java, C++, Python, C#
10
2. Data and Functions Relationship
Structured Programming:
o Data and functions are separate. Functions operate on the data passed to them but
don't belong to any specific data structure.
o Example: A function calculateArea(length, width) operates on the parameters
provided but is not tied to a specific rectangle object.
Object-Oriented Programming:
o Data and functions (methods) are bundled together within objects. Each object
contains the data (attributes) and the methods (functions) that operate on that
data.
o Example: A Rectangle class might have attributes length and width and a method
calculateArea() that operates on those attributes.
3. Code Reusability
Structured Programming:
o Code reusability is achieved through functions and procedures. However, reusability
is more limited compared to OOP.
o Example: A function calculateTax() can be reused, but to handle different types of
taxes, multiple versions might be needed.
Object-Oriented Programming:
o Code reusability is enhanced through inheritance and polymorphism. Classes can
inherit properties and behaviors from other classes, and methods can be overridden
to provide specialized behavior.
o Example: A Vehicle class can be reused to create Car, Truck, and Motorcycle
subclasses, each with specialized behavior.
4. Modularity
Structured Programming:
o Modularity is achieved by breaking the program into functions or procedures. Each
function handles a specific task.
o Example: A function processOrder() might handle everything related to order
processing.
Object-Oriented Programming:
o Modularity is achieved through classes and objects. Each class represents a module
that contains both data and the methods that operate on it.
o Example: A class Order might have methods like process(), validate(), and ship()
encapsulated within the same module.
5. Data Handling
Structured Programming:
o Data is usually global or passed around as parameters between functions. This can
lead to issues like data corruption or difficulty in tracking data flow.
o Example: A global variable totalSales might be updated by multiple functions,
leading to potential errors.
Object-Oriented Programming:
11
o Data is encapsulated within objects, and access is controlled through methods. This
provides better data protection and integrity.
o Example: A BankAccount class encapsulates the balance attribute and provides
methods to safely deposit() or withdraw() money.
6. Complexity Management
Structured Programming:
o Works well for simpler, linear programs. As programs grow in complexity, managing
and maintaining the code can become challenging.
o Example: A large system might require extensive use of global variables and
complex functions, leading to "spaghetti code."
Object-Oriented Programming:
o Better suited for complex systems where different components interact. OOP helps
manage complexity through the organization of code into classes and objects.
o Example: A large-scale application like an online shopping platform can be managed
using classes for User, Product, Cart, Order, etc., each handling its own
responsibilities.
Summary
Structured Programming focuses on the logical flow of the program and organizes code
into functions or procedures, emphasizing sequence, selection, iteration, and modularity.
Object-Oriented Programming (OOP) focuses on modeling real-world entities as
objects, organizing code into classes and objects that encapsulate data and behavior,
emphasizing encapsulation, abstraction, inheritance, and polymorphism.
The Java Development Kit (JDK) is a comprehensive software development kit used for developing Java
applications. It includes a variety of tools and libraries necessary for Java development, making it a
fundamental component for Java developers.
1. Java Compiler (javac): Converts Java source code into bytecode (Java class files) that the Java
Virtual Machine (JVM) can execute.
2. Java Runtime Environment (JRE): Includes the JVM and standard libraries needed to run Java
applications. The JRE is also included in the JDK.
3. Java Virtual Machine (JVM): Executes the bytecode and runs the Java applications.
4. Java Standard Library: A set of pre-written classes and methods that you can use to perform
common programming tasks, such as handling data structures, networking, and user interfaces.
5. Development Tools: Includes tools for debugging (jdb), documentation (javadoc), packaging (jar),
more.
Imagine you’re a carpenter building furniture. To do your job efficiently, you need various
tools and materials:
12
1. Blueprints: To design and understand what you're building.
2. Tools: Such as saws, hammers, and screwdrivers to actually create the furniture.
3. Materials: Wood, nails, screws, etc.
In this analogy:
1. Writing Code: You start by writing Java code in a text editor or an Integrated Development
Environment (IDE). For example, you might write a simple "Hello World" program.
2. Compiling Code: You use the Java compiler (javac) included in the JDK to compile your code into
bytecode. This step is like converting your design into actual wooden pieces that fit together.
3. Running Code: The bytecode is executed by the Java Virtual Machine (JVM), which is part of the
JDK. This is akin to assembling the furniture based on the pieces and instructions you have.
4. Debugging and Documenting: You use additional tools included in the JDK, such as jdb for
debugging and javadoc for generating documentation, to ensure your application works correctly
and is well-documented.
Summary
The JDK is essential for Java development, providing all the necessary tools to write, compile, and
run Java applications. It includes the compiler, libraries, JVM, and additional development tools,
akin to having a complete set of tools and materials for building furniture in a carpentry
workshop.
Java, C, and C++ are three popular programming languages, each with distinct features and use
cases. Here’s a comparative analysis of Java with C and C++, using real-life examples to
illustrate the differences:
1. Memory Management
C:
o Example: Imagine you’re managing a warehouse with a manual inventory system.
You need to track every item’s location and quantity yourself. If you make a
mistake, it could cause confusion or errors in inventory.
o Explanation: In C, memory management is manual. You allocate and deallocate
memory using malloc() and free(). This gives you control but also requires careful
handling to avoid memory leaks or errors.
C++:
o Example: Similar to the warehouse example, but you have a more advanced
inventory system with some automated tools that help you manage stock levels. It
still requires you to monitor the system closely.
13
o Explanation: C++ extends C by adding object-oriented features but still requires
manual memory management. You use new and delete to manage memory, similar
to malloc() and free() in C.
Java:
o Example: You have an automated warehouse management system that tracks
inventory for you. It handles all the details and errors, so you only interact with the
high-level features.
o Explanation: Java uses automatic garbage collection. You don’t need to manually
allocate or deallocate memory. The Java Virtual Machine (JVM) manages memory
automatically, reducing the risk of memory leaks and errors.
2. Object-Oriented Programming
C:
o Example: You’re working with a simple tool like a calculator. It performs basic
operations but doesn’t manage complex interactions or states.
o Explanation: C is procedural and doesn’t support object-oriented features like
classes and inheritance. It focuses on functions and structured programming.
C++:
o Example: Upgrading to a more advanced calculator that supports scientific
functions and can be extended with new features, all while keeping the old ones.
You can also customize it for different users.
o Explanation: C++ supports both procedural and object-oriented programming. It
allows you to define classes, use inheritance, and create objects, making it more
versatile for complex systems.
Java:
o Example: Using a sophisticated calculator app that not only performs calculations
but also interacts with other apps and adapts to different user needs seamlessly.
o Explanation: Java is inherently object-oriented. Everything in Java revolves around
objects and classes. It supports encapsulation, inheritance, and polymorphism,
making it well-suited for complex applications and large systems.
3. Platform Independence
C:
o Example: You build a custom application for a specific type of hardware. It’s
optimized for that hardware but needs to be rewritten or adapted for other types.
o Explanation: C code is compiled into machine code specific to a platform. This
means that the same code may need to be recompiled for different platforms or
operating systems.
C++:
o Example: Similar to the C application but with added features that need careful
adaptation to different hardware or OS environments.
o Explanation: C++ also compiles to platform-specific machine code. While it adds
object-oriented features, it still requires adaptation for different platforms.
14
Java:
o Example: Building a web application that runs on any device with a web browser.
You write it once, and it works everywhere without modification.
o Explanation: Java code is compiled into bytecode, which runs on the Java Virtual
Machine (JVM). This makes Java applications platform-independent; they can run on
any device with a compatible JVM.
4. Exception Handling
C:
o Example: You’re using a basic toolkit that doesn’t have error-checking features. If
something goes wrong, you need to manually check for errors and handle them.
o Explanation: C doesn’t have built-in exception handling. Error handling is typically
done through return codes and manual checks, which can be less intuitive and
error-prone.
C++:
o Example: Upgrading to a toolkit that includes some built-in error handling, but you
still need to manage errors manually and integrate them into your code.
o Explanation: C++ introduces exception handling with try, catch, and throw. This
allows for more structured and readable error handling compared to C.
Java:
o Example: Using a tool that automatically handles errors and exceptions for you. If
something goes wrong, the tool has a built-in system for catching and resolving
issues.
o Explanation: Java has robust exception handling built into the language. It forces
you to handle exceptions using try, catch, and finally blocks, which helps in
managing errors more systematically.
5. Standard Libraries
C:
o Example: Using a basic toolkit with a limited set of features for managing strings,
files, and data structures. You might need to build additional tools yourself.
o Explanation: C has a standard library with basic functions for operations like string
manipulation and file handling, but it’s minimal compared to more modern
languages.
C++:
o Example: Upgrading to a toolkit that includes more advanced features like
containers and algorithms. It makes some tasks easier but still requires
understanding the underlying details.
o Explanation: C++ extends the C standard library with the Standard Template
Library (STL), which includes useful data structures like vectors, lists, and maps,
along with algorithms. This enhances productivity and code reuse.
Java:
15
o Example: Using a comprehensive library that includes everything you need, from
networking to user interfaces. It significantly reduces the need for custom
implementations.
o Explanation: Java comes with a rich standard library (Java Standard Edition API)
that covers a wide range of functionalities, including networking, file I/O, graphical
user interfaces, and more. This extensive library facilitates rapid development and
integration.
Summary
Each language has its strengths and ideal use cases, depending on the specific needs and
constraints of the project.
Applications of JAVA
A Library Management System is a software application used to manage a library's books, patrons, and
borrowing processes. This system can be designed using OOP principles to handle various tasks efficiently.
16
Key Components of the System
1. Adding Books: The librarian adds new books to the system using the Library class. Each book is
represented by a Book object with details like title, author, and availability.
2. Registering Patrons: Library staff registers new members using the Patron class. Each patron has
a unique library ID and personal information.
3. Borrowing Books: When a patron borrows a book, the Loan class handles the borrowing process.
The book's availability is updated, and the loan details are recorded.
4. Returning Books: When a book is returned, the Loan class updates the book's availability, and the
Library class ensures the return process is completed.
5. Viewing Available Books: The library staff can view all available books through the Library class,
which filters out books that are currently borrowed.
An Online Shopping System allows users to browse products, add items to a shopping cart, and complete
purchases. OOP principles can be used to manage the complexity of this system effectively. Key
Components of the System
1. Adding Products: The store manager adds new products to the inventory using the Product class,
specifying details like name, price, and stock level.
2. Customer Registration: Users register as customers with details managed by the Customer class.
This information is used for order processing and communication.
3. Shopping Cart Management: Customers add items to their shopping cart using the ShoppingCart
class. The cart keeps track of products and quantities selected.
4. Placing Orders: When a customer is ready to purchase, the Order class handles the order process,
updating product stock and recording the purchased items.
5. Viewing Order Details: After completing an order, the Order class provides a summary of the
purchase, including customer details and purchased products.
An Online Banking System is an application that allows users to manage their bank accounts, perform
transactions, and monitor their financial activities. OOP principles are ideal for modeling the various
aspects of banking operations.
17
o Customer: Represents a bank customer with personal and account details.
o Transaction: Manages individual transactions between accounts.
o Bank: Manages overall banking operations and account management.
1. Account Management: Customers can create and manage their bank accounts using the Account
class, which handles operations like deposits and withdrawals.
2. Customer Details: Customer information is managed through the Customer class, including
personal and account-related details.
3. Transactions: When transferring funds between accounts, the Transaction class manages the
process, ensuring that the source account is debited and the destination account is credited.
4. Bank Operations: The Bank class oversees overall banking operations, such as adding accounts,
registering customers, and performing fund transfers.
4.E-learning Platform
An E-learning Platform is an application that provides educational courses and resources to users. It
manages course enrollment, content delivery, and user progress.
1. Course Management: The platform allows administrators or teachers to create and manage
courses using the Course class, which includes adding modules and content.
2. User Management: Users, whether students or teachers, are managed using the User class, with
details such as their role and username.
3. Enrollment: Students can enroll in courses, and this process is managed by the Enrollment class,
linking users with courses and recording their participation.
4. Platform Operations: The Platform class handles overall operations, such as adding courses,
registering users, and managing enrollments.
18