OBJECT-ORIENTED PROGRAMMING
WITH JAVA
Concepts, Classes, Objects, Inheritance, Polymorphism, Interfaces, Exceptions
and More
Study Material for Computer Science & Engineering Students
TABLE OF CONTENTS
1. Introduction to Object-Oriented Programming
2. Introduction to Java
3. Java Program Structure and Data Types
4. Classes and Objects
5. Constructors and Methods
6. Encapsulation
7. Inheritance
8. Polymorphism
9. Abstraction
10. Interfaces
11. Packages and Access Modifiers
12. this, super, static and final
13. Exception Handling
14. Strings and Arrays
15. Collections Framework
16. Multithreading
17. File Handling
18. JDBC Basics
19. Java Memory Management
20. Applications, Advantages and Challenges
21. Key Terms and Review Questions
1. INTRODUCTION TO OBJECT-
ORIENTED PROGRAMMING
Object-Oriented Programming (OOP) is a programming paradigm that organizes software
around objects rather than only around functions and procedures. An object represents an entity
with data and behavior. OOP helps programmers model real-world concepts and develop
software that is modular, reusable and easier to maintain.
The four fundamental principles of OOP are Encapsulation, Inheritance, Polymorphism and
Abstraction.
Encapsulation
Encapsulation means combining data and methods inside a class while controlling access to the
internal details of the object.
Inheritance
Inheritance allows a new class to acquire properties and behaviors from an existing class. It
promotes code reuse.
Polymorphism
Polymorphism means "many forms." It allows the same method or interface to perform different
operations depending on the object.
Abstraction
Abstraction means hiding unnecessary implementation details and exposing only the essential
features of an object.
2. INTRODUCTION TO JAVA
Java is a high-level, object-oriented programming language widely used for developing desktop
applications, web applications, enterprise software, mobile applications and distributed systems.
Java source code is compiled into bytecode, which is executed by the Java Virtual Machine
(JVM). This provides Java with significant portability across operating systems that support a
compatible JVM.
Features of Java
Simple: Java has a relatively clear syntax and removes several complex features found in
some older languages.
Object-Oriented: Java is based heavily on classes and objects.
Platform Independent: Java bytecode can execute on different platforms using a
compatible JVM.
Secure: Java provides various runtime and language-level security mechanisms.
Robust: Strong type checking, exception handling and automatic memory management
support reliable applications.
Multithreaded: Java provides built-in support for concurrent programming.
Portable: Java programs can be transferred between supported platforms.
High Performance: Modern JVMs use techniques such as Just-In-Time compilation to
improve execution performance.
JDK, JRE and JVM
JDK
Java Development Kit (JDK) contains tools required for developing Java programs, including
the Java compiler and runtime tools.
JRE
Java Runtime Environment (JRE) provides the runtime components required to execute Java
applications.
JVM
Java Virtual Machine (JVM) executes Java bytecode and provides the runtime environment for
Java programs.
3. JAVA PROGRAM STRUCTURE AND
DATA TYPES
A Java program normally contains one or more classes. A standalone application traditionally
starts execution through the main() method.
Basic Java Program
class Hello {
public static void main(String[] args) {
[Link]("Hello World");
}
}
The class keyword defines a class. The main() method is the traditional entry point for a
standalone Java application. [Link]() displays output.
Java Data Types
Java data types are broadly classified into:
Primitive Data Types
byte
short
int
long
float
double
char
boolean
Reference Data Types
Reference types include:
Classes
Objects
Arrays
Interfaces
Enumerations
Control Statements
Java provides several control statements.
Conditional Statements
if
if-else
else-if
switch
Looping Statements
for
while
do-while
Jump Statements
break
continue
return
4. CLASSES AND OBJECTS
A class is a blueprint or template used to create objects. It defines the properties and behaviors
that objects of that class can have.
An object is an instance of a class. It contains its own state and can perform operations defined
by its class.
Example
class Student {
int id;
String name;
void display() {
[Link](id + " " + name);
}
}
class Main {
public static void main(String[] args) {
Student s1 = new Student();
[Link] = 101;
[Link] = "Rahul";
[Link]();
}
}
Here, Student is a class and s1 is an object of the Student class.
Objects are generally created using the new operator.
5. CONSTRUCTORS AND METHODS
Constructor
A constructor is a special member of a class that is used to initialize objects.
A constructor:
Has the same name as the class.
Does not have a return type.
Is called automatically when an object is created.
Example
class Student {
int id;
String name;
Student(int i, String n) {
id = i;
name = n;
}
}
Types of Constructors
Default Constructor
A constructor supplied by the compiler when no constructor is explicitly declared.
Parameterized Constructor
A constructor that accepts parameters.
Student(int id, String name) {
[Link] = id;
[Link] = name;
}
Constructor Overloading
A class can have multiple constructors with different parameter lists.
Methods
A method is a block of code that performs a specific operation.
void display() {
[Link]("Student Details");
}
Methods improve code organization and reusability.
6. ENCAPSULATION
Encapsulation is one of the most important principles of OOP. It means wrapping data and
methods into a single unit, usually a class.
Data members are commonly declared private, and access is provided through public methods.
Example
class Student {
private int marks;
public void setMarks(int marks) {
[Link] = marks;
}
public int getMarks() {
return marks;
}
}
Here, marks cannot be accessed directly from outside the class.
Advantages of Encapsulation
Protects data.
Provides controlled access.
Improves security.
Makes code easier to maintain.
Allows validation before changing data.
7. INHERITANCE
Inheritance is a mechanism by which one class acquires properties and methods from another
class.
The existing class is called the superclass or parent class. The new class is called the subclass or
child class.
Java uses the extends keyword for class inheritance.
Example
class Animal {
void eat() {
[Link]("Eating");
}
}
class Dog extends Animal {
void bark() {
[Link]("Barking");
}
}
The Dog class inherits the eat() method from Animal.
Types of Inheritance
Single Inheritance
One child class inherits from one parent class.
Multilevel Inheritance
A class inherits from another class which itself inherits from another class.
Hierarchical Inheritance
Multiple classes inherit from the same parent class.
Java does not support multiple inheritance of classes directly. Multiple behavioral contracts can
be achieved using interfaces.
Advantages of Inheritance
Code reuse
Reduced duplication
Easy maintenance
Supports polymorphism
Helps organize related classes
8. POLYMORPHISM
Polymorphism means many forms. It allows one interface or method name to represent different
behaviors.
There are two major forms of polymorphism in Java.
Compile-Time Polymorphism
Compile-time polymorphism is commonly achieved through method overloading.
class Calculator {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
Both methods have the same name but different parameter lists.
Runtime Polymorphism
Runtime polymorphism is commonly achieved through method overriding.
class Animal {
void sound() {
[Link]("Animal sound");
}
}
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
}
}
When a subclass provides its own implementation of an inherited method, the subclass method
can be selected at runtime.
9. ABSTRACTION
Abstraction means hiding implementation details and showing only essential functionality.
Java supports abstraction mainly through:
1. Abstract classes
2. Interfaces
Abstract Class
An abstract class is declared using the abstract keyword.
abstract class Animal {
abstract void sound();
void eat() {
[Link]("Eating");
}
}
An abstract method does not contain an implementation in the abstract class. Subclasses
normally provide the implementation.
Advantages of Abstraction
Reduces complexity.
Hides implementation details.
Improves security and design.
Supports loose coupling.
Makes programs easier to maintain.
10. INTERFACES
An interface defines a contract that implementing classes agree to follow.
A class uses the implements keyword to implement an interface.
Example
interface Vehicle {
void start();
}
class Car implements Vehicle {
public void start() {
[Link]("Car starts");
}
}
Interfaces are useful for abstraction and polymorphism.
A Java class can implement multiple interfaces, which provides a way to combine multiple
behavioral contracts without multiple class inheritance.
Advantages of Interfaces
Provides abstraction.
Supports loose coupling.
Supports multiple interface implementation.
Promotes flexible software design.
Useful in large applications and frameworks.
11. PACKAGES AND ACCESS MODIFIERS
A package is a collection of related Java classes and interfaces.
Packages help:
Organize programs.
Avoid naming conflicts.
Control access.
Improve maintainability.
Access Modifiers
Java provides four commonly discussed access levels.
Private
Accessible only within the declaring class.
Default
When no access modifier is specified, access is generally limited to the same package.
Protected
Accessible within the same package and, under Java's inheritance rules, from subclasses.
Public
Accessible from classes that can access the declaring type.
12. this, super, static AND final
this Keyword
this refers to the current object.
class Student {
int id;
Student(int id) {
[Link] = id;
}
}
It is useful when instance variables and parameters have the same name.
super Keyword
super refers to the superclass portion of an object.
It can be used to:
Access superclass variables.
Call superclass methods.
Invoke superclass constructors.
static Keyword
A static member belongs to the class rather than to individual objects.
class Student {
static String college = "ABC College";
}
The static variable is shared by the relevant objects of the class.
final Keyword
The final keyword can be used with variables, methods and classes.
A final variable cannot be reassigned after initialization.
A final method cannot be overridden.
A final class cannot be inherited.
13. EXCEPTION HANDLING
An exception is an event that interrupts the normal flow of program execution.
Java provides exception-handling mechanisms to deal with abnormal situations.
Important Keywords
try
Contains code that may generate an exception.
catch
Handles an exception.
finally
Contains code that is normally executed after exception processing.
throw
Used to explicitly throw an exception.
throws
Used to declare exceptions that a method may pass to its caller.
Example
class Test {
public static void main(String[] args) {
try {
int a = 10 / 0;
}
catch (ArithmeticException e) {
[Link]("Cannot divide by zero");
}
}
}
Types of Exceptions
Checked Exceptions
These are checked by the compiler and generally must be handled or declared.
Unchecked Exceptions
These occur at runtime and are generally represented by RuntimeException and its subclasses.
Advantages of Exception Handling
Prevents abnormal program termination in many cases.
Separates error-handling logic from normal logic.
Improves program reliability.
Makes debugging and maintenance easier.
14. STRINGS AND ARRAYS
Strings
A String represents a sequence of characters.
String name = "Java";
Java String objects are immutable, meaning their contents cannot be changed after creation.
Common String methods include:
length()
charAt()
substring()
equals()
equalsIgnoreCase()
toUpperCase()
toLowerCase()
indexOf()
StringBuilder
StringBuilder is useful when many modifications to a character sequence are required.
Arrays
An array is a collection of elements of the same type with a fixed size.
int[] marks = {80, 90, 75, 88};
Array indexing begins at zero.
Java supports:
One-dimensional arrays
Two-dimensional arrays
Multidimensional arrays
15. COLLECTIONS FRAMEWORK
The Java Collections Framework provides ready-to-use interfaces and classes for storing and
manipulating groups of objects.
List
A List is an ordered collection that can contain duplicate elements.
Examples:
ArrayList
LinkedList
Set
A Set is designed to store unique elements.
Examples:
HashSet
LinkedHashSet
TreeSet
Map
A Map stores key-value pairs.
Examples:
HashMap
LinkedHashMap
TreeMap
Queue
A Queue is used for holding elements before processing.
Collections provide reusable data structures and algorithms and reduce the amount of code
developers need to write.
16. MULTITHREADING
Multithreading is the execution of multiple threads within a program.
A thread is a lightweight unit of execution.
Java provides several mechanisms for creating and managing threads.
Creating a Thread
One traditional approach is to extend the Thread class.
class MyThread extends Thread {
public void run() {
[Link]("Thread is running");
}
}
Another common approach is implementing Runnable.
class MyTask implements Runnable {
public void run() {
[Link]("Task is running");
}
}
Advantages of Multithreading
Improved responsiveness.
Better resource utilization.
Concurrent execution of independent tasks.
Useful for server and application development.
However, shared data can cause race conditions, so synchronization may be necessary.
17. FILE HANDLING
Java provides APIs for creating, reading, writing and manipulating files.
The [Link] package provides traditional stream-based file handling.
The [Link] package provides modern file and path operations.
Common File Operations
Create a file.
Read data.
Write data.
Append data.
Delete a file.
Create directories.
Check file properties.
Example
import [Link];
class FileExample {
public static void main(String[] args) {
File file = new File("[Link]");
if ([Link]()) {
[Link]("File exists");
}
}
}
Try-with-resources is commonly used to ensure that resources such as files are properly closed.
18. JDBC BASICS
JDBC (Java Database Connectivity) is an API that allows Java applications to communicate
with relational databases.
A typical JDBC process involves:
1. Loading or accessing the required database driver.
2. Establishing a database connection.
3. Creating a Statement or PreparedStatement.
4. Executing SQL.
5. Processing the result when required.
6. Closing resources.
PreparedStatement
PreparedStatement is commonly preferred for parameterized SQL queries.
It helps separate SQL structure from parameter values and can help prevent SQL injection when
used correctly.
JDBC is useful for developing database-driven Java applications such as:
Student management systems
Banking applications
Inventory systems
Library systems
E-commerce applications
19. JAVA MEMORY MANAGEMENT
Java provides automatic memory management through garbage collection.
When objects are created, memory is allocated for them by the Java runtime. When objects are
no longer reachable, the garbage collector can eventually reclaim their memory.
Garbage Collection
Garbage collection automatically identifies objects that are no longer reachable by the
application and reclaims their memory.
Advantages include:
Reduces manual memory management.
Helps prevent many types of memory-management errors.
Simplifies application development.
However, programmers must still manage external resources such as:
Files
Database connections
Network connections
Streams
These resources should be closed appropriately.
20. APPLICATIONS, ADVANTAGES AND
CHALLENGES
Applications of Java
Java is used in many areas, including:
Enterprise applications
Web applications
Backend development
Android development
Desktop applications
Cloud applications
Distributed systems
Scientific applications
Educational software
Server-side applications
Advantages of Java
Object-oriented programming support.
Platform independence through the Java platform.
Automatic memory management.
Strong type checking.
Exception handling.
Multithreading support.
Large standard library.
Large ecosystem of tools and frameworks.
Good support for enterprise application development.
Challenges of Java
Memory consumption can be significant for some applications.
Multithreaded applications can be difficult to design and debug.
Poorly designed inheritance can increase complexity.
Large frameworks require continuous learning.
Incorrect resource management can cause performance and reliability problems.
21. KEY TERMS
Term Meaning
Class Blueprint defining the structure and behavior of objects
Object Instance of a class
Encapsulation Combining data and methods while controlling access
Inheritance Mechanism for deriving a class from another class
Polymorphism Ability of an interface or operation to have different behavior
Abstraction Hiding implementation details
Interface A contract implemented by classes
Constructor Special member used to initialize objects
Exception Event that disrupts normal program execution
JVM Java Virtual Machine that executes Java bytecode
JDK Java Development Kit used for Java development
JRE Java Runtime Environment used to run Java applications
Package Group of related Java classes and interfaces
Thread Lightweight unit of execution
JDBC Java API for database connectivity
REVIEW QUESTIONS
1. What is Object-Oriented Programming? Explain its four major principles.
2. What is Java? Explain the important features of Java.
3. Differentiate between JDK, JRE and JVM.
4. What is a class? What is an object?
5. Explain constructors and their types.
6. What is constructor overloading?
7. Explain encapsulation with a suitable example.
8. What is inheritance? Explain different types of inheritance.
9. Differentiate between method overloading and method overriding.
10. Explain compile-time and runtime polymorphism.
11. What is abstraction? Explain abstract classes.
12. What is an interface? Explain its advantages.
13. Explain Java access modifiers.
14. Explain the uses of this, super, static and final.
15. What is exception handling? Explain try, catch, finally, throw and throws.
16. Differentiate between checked and unchecked exceptions.
17. What is a String? Explain important String methods.
18. What is an array? Explain one-dimensional and multidimensional arrays.
19. Explain the Java Collections Framework.
20. Differentiate between List, Set and Map.
21. What is multithreading? Explain its advantages.
22. Explain the different ways of creating threads in Java.
23. What is file handling? Explain common file operations.
24. What is JDBC? Explain the steps involved in database connectivity.
25. Explain Java memory management and garbage collection.
26. List the major applications of Java.
27. Explain the advantages and challenges of Java.
CONCLUSION
Object-Oriented Programming with Java provides a strong foundation for developing modular,
reusable and maintainable software. The concepts of classes, objects, encapsulation,
inheritance, polymorphism, abstraction and interfaces form the core of Java programming.
By learning exception handling, collections, multithreading, file handling and JDBC, students
can progress from basic Java programs to larger and more practical applications. A strong
understanding of OOP concepts is therefore essential for students of Computer Science and
Engineering and provides a foundation for learning advanced Java frameworks and software
development technologies.