0% found this document useful (0 votes)
9 views20 pages

Oops With Java Unit 1-1

Java is a high-level, platform-independent programming language developed by James Gosling in 1995, known for its object-oriented features, robustness, and rich API. It is widely used for various applications including desktop, web, and mobile development, supported by the Java Virtual Machine (JVM). Key concepts of Java include classes, objects, encapsulation, inheritance, and polymorphism, which facilitate code reusability and maintenance.
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)
9 views20 pages

Oops With Java Unit 1-1

Java is a high-level, platform-independent programming language developed by James Gosling in 1995, known for its object-oriented features, robustness, and rich API. It is widely used for various applications including desktop, web, and mobile development, supported by the Java Virtual Machine (JVM). Key concepts of Java include classes, objects, encapsulation, inheritance, and polymorphism, which facilitate code reusability and maintenance.
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

UNIT=1

INTRODUCTION:
• Java is a general –Purpose Programming Language.
• It is High Level Language.
• Java was originally developed by James Gosling at Sun Microsystems in 1995.
• Java is a Language that is Platform independent.
• A Platform is the hardware and Software environment in which a Programs run.
• Java has irs own Runtime Environment(JRE) and API.
• Java code is once compiled; it can run on any platform without recompiling or any
kind of modification.
• “write Once Run anywhere”
• Java is supported by Java Virtual Machine(JVM).
It is mostly used for building desktop applications, web applications, Android apps and
enterprise systems.

Features of Java:
• Object-Oriented Programming (OOP): Java supports OOP concepts to create modular
and reusable code.

• Platform Independence: Java programs can run on any operating system with a JVM.

• Robust and Secure: Java ensures reliability and security through strong memory
management and exception handling.

• Multithreading and Concurrency: Java allows concurrent execution of multiple tasks for
efficiency.

• Rich API and Standard Libraries: Java provides extensive built-in libraries for various
programming needs.

• Frameworks for Enterprise and Web Development: Java supports frameworks that
simplify enterprise and web application development.

• Open-Source Libraries: Java has a wide range of libraries to extend functionality and
speed up development.

• Maintainability and Scalability: Java’s structured design allows easy maintenance and
growth of applications.

Understanding the Hello World Program in Java

When we learn any programming language, the first step is writing a simple program to
display "Hello World". So, here is a simple Java program that displays "Hello World" on
the screen.
// A Java program to print Hello World!
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello World!");
}
}

Output
Hello World!
Explanation:

Hello World Program Explanation:


How to run the above code?
• Write code in a file like [Link].
• Java Compiler "javac" compiles it into bytecode "[Link]".
• JVM (Java Virtual Machine) reads the .class file and interprets the bytecode.
• JVM converts bytecode to machine readable code i.e. "binary" (001001010) and then
execute the program.
HOW JAVA CODE EXECUTE:
Comments in Java:
Comments are the notes written inside the code to explain what we are doing. The comment
lines are not executed while we run the program.

Single-line comment

// This is a comment

Multi-line comment

/*
This is a multi-line comment.
This is useful for explaining larger sections of code.
*/
Famous Applications Built Using Java
• Android Apps: Most of the Android mobile apps are built using Java.
• Netflix: This uses Java for content delivery and backend services.
• Amazon: Java language is used for its backend systems.
• LinkedIn: This uses Java for handling high traffic and scalability.
• Minecraft: This is one of the world’s most popular games that is built in Java.
• Spotify: This uses Java in parts of its server-side infrastructure.
• Uber: Java is used for backend services like trip management.
• NASA WorldWind: This is a virtual globe software built using Java.

What Can We Do with Java?


Java is used for:
• Mobile App Development: Android development using Android Studio.
• Web Development: Using frameworks like Spring, Spring Boot, Struts, Hibernate
• Desktop GUI Applications: With libraries like JavaFX and Swing.
• Enterprise Applications: Backbone of banking, ERP and large-scale business software.
• Game Development: With engines like LibGDX and jMonkeyEngine.
• Big Data Technologies: Like Hadoop and Apache Kafka.
• Internet of Things (IoT): Java can run on embedded systems and devices.
• Cloud-based Applications: Java is used in services on AWS, Azure and Google Cloud.
• Scientific Applications: Java is used in tools that process large amounts of scientific data.

What is Object-Oriented Programming?


Object-Oriented Programming (OOP) is a paradigm that is widely used in software development.
Moreover, it uses objects that can represent abstract concepts or real-world objects to represent and
manipulate data, including the actions that can be performed. In OOP, a program is made up of a collection
of objects that communicate with each other by sending messages.

The following applications get structured around objects using OOP systems.

Client-Server Systems

IT infrastructure is made up of object-oriented client-server systems, which are used to make Object-
Oriented Client-Server Internet (OCSI) applications.
Object-Oriented Database

The object-oriented database stores objects, such as integers and real numbers,

Introduction of Object Oriented Programming:


As the name suggests, Object-Oriented Programming or OOPs refers to languages that use
objects in programming.
Object-oriented programming aims to implement real-world entities like inheritance, hiding,
polymorphism, etc in programming.
The main aim of OOP is to bind together the data and the functions that operate on them so that
no other part of the code can access this data except that function.
OOPs Concepts:
• Class
• Objects
• Data Abstraction
• Encapsulation
• Inheritance
• Polymorphism
• Dynamic Binding
• Message Passing

1. Class:
A class is a user-defined data type. It consists of data members and member functions, which
can be accessed and used by creating an instance of that class. It represents the set of properties
or methods that are common to all objects of one type. A class is like a blueprint for an object.
For Example: Consider the Class of Cars. There may be many cars with different names and
brands but all of them will share some common properties like all of them will have 4 wheels,
Speed Limit, Mileage range, etc. So here, Car is the class, and wheels, speed limits, mileage are
their properties.

2. Object:
It is a basic unit of Object-Oriented Programming and represents the real-life entities. An Object
is an instance of a Class. When a class is defined, no memory is allocated but when it is
instantiated (i.e. an object is created) memory is allocated. An object has an identity, state, and
behavior. Each object contains data and code to manipulate the data. Objects can interact without
having to know details of each other’s data or code, it is sufficient to know the type of message
accepted and type of response returned by the objects.
For example “Dog” is a real-life Object, which has some characteristics like color, Breed, Bark,
Sleep, and Eats.
3. Data Abstraction:
• Data abstraction is one of the most essential and important features of object-oriented
programming.
• Data abstraction refers to providing only essential information about the data to the
outside world, hiding the background details or implementation.
• Consider a real-life example of a man driving a car. The man only knows that pressing
the accelerators will increase the speed of the car or applying brakes will stop the car, but
he does not know about how on pressing the accelerator the speed is increasing, he does
not know about the inner mechanism of the car or the implementation of the accelerator,
brakes, etc in the car. This is what abstraction is.
4. Encapsulation:
• Encapsulation is defined as the wrapping up of data under a single unit.
• It is the mechanism that binds together code and the data it manipulates.
• In Encapsulation, the variables or data of a class are hidden from any other class and can
be accessed only through any member function of their class in which they are declared.
• As in encapsulation, the data in a class is hidden from other classes, so it is also known
as data-hiding.

Consider a real-life example of encapsulation, in a company, there are different sections like the
accounts section, finance section, sales section, etc.
The finance section handles all the financial transactions and keeps records of all the data related
to finance.
Similarly, the sales section handles all the sales-related activities and keeps records of all the
sales.
Now there may arise a situation when for some reason an official from the finance section needs
all the data about sales in a particular month.
In this case, he is not allowed to directly access the data of the sales section. He will first have
to contact some other officer in the sales section and then request him to give the particular data.
This is what encapsulation is. Here the data of the sales section and the employees that can
manipulate them are wrapped under a single name “sales section”.
5. Inheritance:
Inheritance is an important pillar of OOP(Object-Oriented Programming).
The capability of a class to derive properties and characteristics from another class is called
Inheritance. When we write a class, we inherit properties from other classes. So when we create
a class, we do not need to write all the properties and functions again and again, as these can be
inherited from another class that possesses it. Inheritance allows the user to reuse the code
whenever possible and reduce its redundancy.
6. Polymorphism:
The word polymorphism means having many forms.
In simple words, we can define polymorphism as the ability of a message to be displayed in more
than one form.
For example, A person at the same time can have different characteristics. Like a man at the
same time is a father, a husband, an employee. So the same person posses different behavior in
different situations. This is called polymorphism.

7. Dynamic Binding: In dynamic binding, the code to be executed in response to the function
call is decided at runtime. Dynamic binding means that the code associated with a given
procedure call is not known until the time of the call at run time. Dynamic Method Binding One
of the main advantages of inheritance is that some derived class D has all the members of its
base class B. Once D is not hiding any of the public members of B, then an object of D can
represent B in any context where a B could be used. This feature is known as subtype
polymorphism.
8. Message Passing: It is a form of communication used in object-oriented programming as well
as parallel programming. Objects communicate with one another by sending and receiving
information to each other. A message for an object is a request for execution of a procedure and
therefore will invoke a function in the receiving object that generates the desired results. Message
passing involves specifying the name of the object, the name of the function, and the information
to be sent.
Why do we need object-oriented programming
• To make the development and maintenance of projects more effortless.
• To provide the feature of data hiding that is good for security concerns.
• We can solve real-world problems if we are using object-oriented programming.
• It ensures code reusability.
• It lets us write generic code: which will work with a range of data, so we don't have to write
basic stuff over and over again.
OOP vs Real Life (Simple Mapping)
OOP Concept Real Life Example
Class Blueprint of a house
Object Actual house
Encapsulation ATM machine
Inheritance Child inherits traits
Polymorphism Same phone button, different functions

Benefits/Advantages of JAVA :
• Straightforward Java - It is anything but difficult to program, compose, gather,
investigate, and learn than elective programming dialects. Java might be a more modest
sum convoluted than C++; therefore, Java utilizes programmed memory portion and trash
assortment.
• Item Oriented - It grants you to make standard projects and reusable code.
• Stage Independent Java code - It runs on any machine that needn't bother with any unique
programming to be introduced, however, the JVM should be available on the machine.
• Java is a disseminated language - Java is a dispersed language as it gives an instrument
for dividing information and projects between numerous PCs that improve the presentation
and proficiency of the framework. The RMI(Remote Method Invocation) is something that
bolsters the dispersed handling in Java.
• Secure Java - It has no unequivocal pointer. Besides this, it is a security administrator that
characterizes the entrance of classes.
• Memory distribution - In Java, memory is part into two sections one is stored and another
is stack. At whatever point we pronounce a variable JVM gives memory from one or the
other stack or pile space. It assists with remaining the information and reestablish it without
any problem.
• Multithreaded - It is the potential for a program to perform numerous assignments
simultaneously. at long last time showed up to become familiar with the ideas of
Multithreading in Java.
• Java gives Automatic Garbage Collection - There is programmed memory for the
executives in Java that is overseen by the Java Virtual Machine(JVM). At whatever point
the articles are not utilized by programs any longer and they don't allude to anything.

Disadvantages of JAVA :
• Execution Java language - It is a more slow language when contrasted with different
dialects as it is a memory burning-through language.

• Java requires huge memory space - Java requires a critical or significant measure of
memory space when contrasted with different dialects like C and C++. During the
execution of trash assortment, the memory productivity and the exhibition of the framework
might be unfavorably influenced.
• Verbose and Complex codes - Java codes are verbose, implying that there are numerous
words in them and there are numerous long and complex sentences that are hard to peruse
and comprehend. This can decrease the meaningfulness of the code.

• Slow Startup Time - Java applications can have slower startup times because of the need
to initialize the JVM and load necessary classes.

• Poor Support for Low-Level Programming - Java abstracts away hardware-level


operations, making it less suitable for system-level programming or applications requiring
direct hardware interaction.
• Less Control Over System Resources - Java's automatic memory management and
garbage collection can lead to less precise control over system resources, which can be
critical for performance-tuned applications.

• Limited Real-Time Capabilities - Java's garbage collection process can introduce pauses
that make it less suitable for real-time systems where consistent response times are crucial.

Difference between JDK, JRE, and JVM


JDK, JRE, and JVM are three components form the core of the Java platform and are
closely related, but each has a distinct role in Java development and execution. Before
learning Java in depth, it is important to understand the difference between JDK, JRE, and
JVM.

In this chapter, we will first learn what are JDK, JRE, and JVM, and how they are different
from each other.

JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it
doesn't physically exist. It is a specification that provides a runtime environment in
which Java bytecode can be executed. It can also run those programs that are written in other
languages and compiled to Java bytecode.

JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are
platform dependent because the configuration of each OS is different from that of others.
However, Java is platform independent. There are three notions of the
JVM: specification, implementation, and instance.

The JVM performs the following main tasks:

o Loads code
o Verifies code
o Executes code
o Provides runtime environment
To read more JVM Architecture

JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java
Runtime Environment is a set of software tools that are used for developing Java applications.
It is used to provide the runtime environment. It is the implementation of JVM. It physically
exists. It contains a set of libraries + other files that the JVM uses at runtime.

The implementation of JVM is also actively released by other companies besides Sun
Microsystems.

JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software
development environment that is used to develop Java applications and applets. It physically
exists. It contains JRE + development tools.

JDK is an implementation of any one of the below given Java Platforms released by Oracle
Corporation:

o Standard Edition Java Platform


o Enterprise Edition Java Platform
o Micro Edition Java Platform
The JDK contains a private Java Virtual Machine (JVM) and a few other resources, such as
an interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator
(Javadoc), etc., to complete the development of a Java Application.
JDK Vs. JRE Vs. JVM
Feature JDK JRE JVM

Definition Java Development Kit Java Runtime Java Virtual Machine


(JDK) is a software Environment (JRE) is a (JVM) is an abstract
development kit used to software package that machine that provides an
develop Java applications. provides Java Virtual environment for the
Machine (JVM), class execution of Java
libraries and other ByteCodes.
components to run
applications in Java.

Functions Provides tools for It provides an The virtual machine that


developing Java environment for runs the bytecode
applications. It includes executing Java generated by the
compiler (javac), JRE, applications. It includes compiler. It's a part of
and debugging tools. JVM and libraries JRE and is platform-
required to run Java dependent but provides a
programs, but does not platform-independent
include development execution environment.
tools.

Use Cases Used by developers to Used by end-users to Converts bytecode into


write, compile, and debug execute Java applications machine code and
Java programs. without needing executes it on the
development tools. underlying hardware.

Platform Dependency It is platform dependent. It is platform dependent. It is platform dependent.

Implementation JDK = JRE + JRE = JVM + Class JVM = provides a runtime


Development tools libraries environment.

JVM (Java Virtual Machine) Architecture:-


JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides a runtime environment
in which Java bytecode can be executed.

What is JVM (Java Virtual Machine)?


JVM stands for Java Virtual Machine and it is:

1. A specification specifying the workings of the Java Virtual Machine. However, the
implementation provider is independent of choosing the algorithm. Oracle and other
companies have provided its implementation.
2. An implementation Its implementation is known as JRE (Java Runtime
Environment).
3. Runtime Instance Whenever we write a java command on the command prompt to
run the Java class, an instance of JVM is created.

Platform Dependency of JVM


JVMs are available for many hardware and software platforms. This means JVM
is platform-dependent, as it is designed specifically for different operating systems and
hardware architectures.
JVM implementations are tailored to specific platforms, allowing them to optimize
performance and ensure compatibility. This design enables Java applications to run
consistently across diverse environments.

Functions of JVM
The JVM performs following operations:

• Verifies code: It checks the bytecode for security and correctness to ensure it does not violate Java’s
safety rules.

• Executes code: The JVM converts bytecode into machine-level instructions and executes them using
the interpreter or JIT compiler.

• Provides a runtime environment: It manages memory, threads, and system resources required to
run Java applications efficiently.

JVM Internal Definitions


JVM Provides Definitions for the:

• Memory areas: The JVM defines memory regions such as heap, stack, method area, and PC register
for program execution.
• Class file format: It specifies a standard structure for .class files so they can be understood by any
JVM.
• Register set: The JVM uses registers like the program counter to track instruction execution.
• Garbage-collected heap: It automatically manages memory by removing unused objects through
garbage collection.
• Fatal error reporting and more: The JVM handles serious runtime errors and provides diagnostic
information for debugging.

JVM Architecture
JVM (Java Virtual Machine) architecture defines how Java programs are loaded, executed,
and managed in memory that ensures platform independence and efficient performance. The
main components of JVM architecture:

1) Classloader:
Classloader is a subsystem of JVM which is used to load class files. Whenever we run the
Java program, it is loaded first by the classloader. There are three built-in classloaders in
Java.

1. Bootstrap ClassLoader: It is the first classloader, which is the superclass of the


Extension classloader. It loads the [Link] file that contains all class files of Java Standard
Edition, such as the [Link] package classes, [Link] package classes, [Link]
package classes, [Link] package classes, [Link] package classes, etc.
2. Extension ClassLoader: It is the child classloader of Bootstrap and the parent
classloader of the System classloader. It loads the jar files located inside the
$JAVA_HOME/jre/lib/ext directory.
3. System/Application ClassLoader: It is the child classloader of the Extension It loads
the classfiles from the classpath. By default, the classpath is set to the current directory.
You can change the classpath using the "-cp" or "-classpath" switch. It is also known
as the Application classloader.
4. Runtime Data Areas: JVM allocates memory for various runtime data areas during
program execution. These include the method area, heap, stack, PC (Program Counter)
register, and native method stacks. The method area stores class structures, method
code, static variables, and constant pool. The heap is where objects are allocated, while
the stack holds method invocation frames. The PC register keeps track of the currently
executing JVM instruction, and native method stacks are used for executing native
methods.
5. Execution Engine: The execution engine is responsible for executing the compiled
Java bytecode. It consists of two components: the interpreter and the just-in-time (JIT)
compiler. The interpreter reads and executes bytecode instructions one by one, while
the JIT compiler compiles frequently executed bytecode sequences into native
machine code for improved performance.
6. Garbage Collector: JVM includes a garbage collector responsible for reclaiming
memory occupied by objects that are no longer in use. The garbage collector identifies
and removes unreachable objects, freeing up memory for new allocations. Various
garbage collection algorithms are available, each with its own trade-offs in terms of
performance and memory overhead.
7. Native Method Interface (JNI): JNI enables Java code to interact with native
libraries and perform operations not directly supported by the Java language. It allows
Java applications to call functions written in languages like C and C++, providing
flexibility and access to platform-specific capabilities.

2) Class (Method) Area:


Class(Method) Area stores per-class structures such as the runtime constant pool, field, and
method data, and the code for methods.

1. Runtime Constant Pool: The runtime constant pool is part of the Class(Method) Area
and consists of constant pool entries. These are used to store symbolic references,
literals, and other constant values required by the class. These include class and
interface names, method and field names, string literals, and numeric literals.
2. Field Data: The Class(Method) Area also stores information about the fields declared
within a class, including their names, types, and access modifiers. This data is used by
the JVM to access and manipulate object fields at runtime.
3. Method Data: Along with field data, the Class(Method) Area contains information
about the methods declared within a class, including their names, return types,
parameter types, and bytecode instructions. This information is used by the JVM to
invoke methods and execute bytecode instructions during program execution.

3) Heap:
The Heap is the runtime data area in which objects are allocated.
1. Object Allocation: The Heap is responsible for allocating memory for objects
dynamically created during program execution. When an object is instantiated using
the new keyword or by invoking a constructor, memory is allocated on the Heap to
store the object's data.
2. Garbage Collection: The Heap is managed by the JVM's garbage collector, which
periodically scans the Heap for objects that are no longer in use or reachable by the
application. Garbage collection involves reclaiming memory occupied by these unused
objects, freeing up space for new allocations.
3. Heap Structure: The Heap is typically divided into two main areas: The Young
Generation and the Old Generation (also known as the Tenured Generation). The
Young Generation is further divided into the Eden Space and Survivor Spaces, while
the Old Generation contains long-lived objects that have survived multiple garbage
collection cycles.

4) Stack:
Java Stack stores frames. It holds local variables and partial results, and plays a part in method
invocation and return.

Each thread has a private JVM stack, created at the same time as thread.

A new frame is created each time a method is invoked. A frame is destroyed when its method
invocation completes.

1. Frame Structure: Each frame contains local variables, operand stacks, and a
reference to the runtime constant pool of the method being executed. Local variables
store method parameters and local variables, while the operand stack is used for
intermediate results and operand manipulation during method execution.
2. Method Invocation: The Stack plays a crucial role in method invocation and return.
When a method is invoked, a new frame is created and pushed onto the stack. Upon
method completion, the frame is popped off the stack, and control returns to the
invoking method.

5) Program Counter Register


PC (program counter) register contains the address of the Java virtual machine instruction
currently being executed.

The Program Counter (PC) register is a special register within the JVM that contains the
memory address of the currently executing instruction.

1. Instruction Pointer: The PC register serves as an instruction pointer, guiding the


JVM through the sequence of bytecode instructions being executed.
2. Thread-specific: Like the Java Stack, each thread in a Java application has its own PC
register, allowing multiple threads to execute instructions concurrently without
interference.

6) Native Method Stack:


It contains all the native methods used in the application.

The Native Method Stack is a memory area within the JVM used for executing native
methods, which are methods written in languages other than Java, such as C or C++.
Additional information about the Native Method Stack includes:
Native Method Invocation: When a Java application invokes a native method, the execution
flow transitions to the Native Method Stack, where the native method's code is executed.

7) Execution Engine
It contains:

1. A virtual processor
2. Interpreter: Read bytecode stream then execute the instructions.
3. Just-In-Time(JIT) Compiler: It is used to improve the performance. JIT compiles
parts of the byte code that have similar functionality at the same time, and hence
reduces the amount of time needed for compilation. Here, the term "compiler" refers
to a translator from the instruction set of a Java virtual machine (JVM) to the
instruction set of a specific CPU.

8) Java Native Interface


Java Native Interface (JNI) is a framework which provides an interface to communicate with
another application written in another language like C, C++, Assembly etc. Java uses JNI
framework to send output to the Console or interact with OS libraries.

OR

How a Java Program Runs with JVM:-


Step 1: Write Java Program
You write the program in a .java file using any editor (Notepad, VS Code, etc.).

Example:
class Test {
public static void main(String[] args) {
[Link]("Hello JVM");
}
}

Step 2: Compile the Program (javac)


Use the Java Compiler:
e.g: javac [Link]

✔ This checks syntax


✔ Converts .java → .class
✔ .class file contains bytecode

Step 3: Class Loader Loads Bytecode


When you run the program:
e.g: java Test

The Class Loader Subsystem loads the .class file into JVM memory.

Types of class loaders:


Bootstrap Class Loader
Extension Class Loader
Application Class Loader
Step 4: Bytecode Verification
JVM verifies the bytecode to ensure:
1) No illegal code
2) No security violations
3) Code follows Java rules

If verification fails → program stops


Step 5: Execution Engine Runs the Code
Execution Engine has:
1️) Interpreter
• Executes bytecode line by line
• Slower but quick to start
2️) JIT Compiler (Just-In-Time)
• Converts frequently used bytecode into machine code
• Improves performance
Step 6: Runtime Memory Areas

During execution, JVM uses memory areas:


1) Method Area – class data, methods
2) Heap – objects
3) Stack – method calls, local variables
4) PC Register
5) Native Method Stack

Step 7: Output on Screen


Finally, the result is displayed on the console:

Hello JVM

Flow Diagram based on JVM:


[Link]
↓ javac
[Link] (Bytecode)

Class Loader

Bytecode Verifier

Execution Engine (Interpreter + JIT)

Output
4-PILLER OF OBJECT ORIENTED PROGRAMMING:

4-Piller of object oriented programming are the core Concepts based on which
oop is based.

Encapsulation
Definition: Encapsulation means wrapping data and methods into a single unit (class) and
hiding data from outside access.
How it is achieved:

Using private variables


Providing access through getters and setters
Example (Java):

class Student {
private int age;
public void setAge(int age) {
[Link] = age;
}

public int getAge() {


return age;
}
}
Real-life example:
ATM Machine – You cannot access internal data directly; you use buttons/options.
2️) Abstraction
Definition: Abstraction means hiding implementation details and showing only essential
features.
How it is achieved:
• Abstract classes
• Interfaces
Example (Java):
interface Vehicle {
void start();
}

class Car implements Vehicle {


public void start() {
[Link]("Car starts with key");
}
}

Real-life example:
Car – You drive using steering, brake, accelerator; internal engine details are hidden.
3️) Inheritance:
Definition: Inheritance allows one class to acquire properties and behaviour of another
class.
Keyword used:
• Extends

Example (Java):

class Animal {
void eat() {
[Link]("Eating");
}
}

class Dog extends Animal {


void bark() {
[Link]("Barking");
}
}
Real-life example:
• Child inherits properties from parents.
4️) Polymorphism
Definition:Polymorphism means one name, many forms.
Types:
Compile-time (Method Overloading)
Run-time (Method Overriding)
Example (Java):

class MathOp {
int add(int a, int b) {
return a + b;
}

int add(int a, int b, int c) {


return a + b + c;
}
}
Real-life example:
Mobile phone – Same button, different functions in different apps.

Security Aspects in Object-Oriented Programming:

Object-Oriented Programming provides better security by controlling access to data and


behavior through its core concepts.
1️) Encapsulation (Data Hiding)
How it provides security:
• Data members are kept private
• Direct access to data is restricted
• Access is allowed only through controlled methods
Example (Java):
class BankAccount {
private double balance;
public double getBalance() {
return balance;
}
}

• Prevents unauthorized modification


• Protects sensitive data
Real-life example:
Bank locker – only authorized access allowed
2️) Access Modifiers (Access Control)
OOP uses access modifiers to define visibility.
Modifier
Access Level
private
Within same class only
default
Within same package
protected
Same package + subclass
public
Anywhere
Security Benefit:
Only required parts of code are exposed, reducing misuse.
3️) Abstraction (Hide Internal Details):
How it provides security:
• Internal logic is hidden
• Users interact only with necessary features
• Prevents misuse of internal implementation
Example:
interface Payment {
void pay();
}
• Users can’t see how payment is processed
• Reduces attack surface
4️) Inheritance with Controlled Access:
How it provides security:
• Only protected/public members are inherited
• private members remain hidden
• Sensitive data remains secure
• Controlled reusability
5️) Polymorphism (Runtime Security):
How it helps security:
• Correct method is called at runtime
• Prevents incorrect behavior execution
• Allows safe method overriding
Example:
Account a = new SavingAccount();
[Link]();
• Ensures correct implementation is used
6️) Immutability (Extra Security Feature):
Objects whose data cannot be changed after creation are more secure.
Example:
final class User {
private final String name;
}
• Prevents data tampering
• Used in security-sensitive applications
7️) Exception Handling:
Security benefit:
• Prevents program crashes
• Avoids exposing system details
• Controls abnormal behavior
• Safe error handling

Sandbox Model (in Object-Oriented Programming):-

Definition: The Sandbox Model is a security mechanism used in Object-Oriented


Programming (especially in Java) where a program is executed in a restricted environment
so that it cannot access system resources directly without permission.
In simple words:
Untrusted code runs inside a “sandbox” with limited permissions.
Why do we use the Sandbox Model?
We use the sandbox model to protect the system from malicious or untrusted code.
Main purposes:
• Prevent unauthorized access
• Protect system files
• Stop harmful operations
• Ensure secure execution of programs
• Maintain data integrity
How Sandbox Model Works (Java)
When a Java program runs:
• Class Loader loads the class
• Bytecode Verifier checks for illegal code
• Security Manager applies restrictions
• Program runs only within allowed permissions
Key Components of Sandbox Model
1️) Class Loader
• Loads classes into JVM
• Prevents replacement of core Java classes
2️) Bytecode Verifier
• Verifies bytecode for security violations
• Ensures no illegal memory access
3️) Security Manager
• Decides what resources a program can access
• Controls file, network, and system access
Diagram of Sandbox Model
User Program / Applet
|
v
+----------------+
| Class Loader |
+----------------+
|
v
+--------------------+
| Bytecode Verifier |
+--------------------+
|
v
+--------------------+
| Security Manager |
+--------------------+
|
v
+--------------------+
| JVM Sandbox |
| (Restricted Area) |
+--------------------+
|
-----------------------
| OS / File System |
| Network / Memory |
-----------------------
Direct Access Denied
🔹 Real-Life Example :

❖ Children playing in a sandbox.


They can play freely inside the sandbox, but cannot go outside and harm themselves or
others.
Same way,
➢ Java program runs freely inside JVM, but cannot harm the system.
Advantages of Sandbox Model
• High security
• Safe execution of untrusted code
• Platform independence
• Protection from viruses and malware

You might also like