OOPs Notes
# Object-Oriented Programming (OOP) in Java
Object-Oriented Programming is a methodology to design a program using classes and
objects. It simplifies software development and maintenance by organizing code into
reusable blueprints.
## Class
A Class is a user-defined blueprint or template from which objects are created. It defines a
set of properties (called fields or attributes) and behaviors (called methods). A class is a
logical entity and doesn't occupy memory until an object is created from it.
Java Syntax (for class):
Java
class Student {
// Data members (fields)
int id;
long mobile;
String name;
// Member function (method)
int add(int x, int y) {
return x + y;
## Object
An Object is a real-world entity and an instance of a class. When a class is defined, no
memory is allocated; but when an object is created, memory is allocated in the heap. An
object has a state (its fields) and behavior (its methods).
Java Syntax (for object):
Java
// Creates an object of the Student class
OOPs Notes
Student s = new Student();
• Note: In Java, objects are almost always created with the new keyword. This allocates
memory on the heap, and the variable s (which is a reference) is stored on the stack.
## The Four Pillars of OOP
### 1. Inheritance
Inheritance is a mechanism where a new class (called a subclass or child class) acquires the
properties and methods of an existing class (called a superclass or parent class). This
promotes code reuse. The extends keyword is used to achieve inheritance.
Java Syntax:
Java
class ChildClass extends ParentClass {
// ...
Types of Inheritance in Java:
1. Single Inheritance: A class inherits from only one superclass.
2. Multilevel Inheritance: A class inherits from a subclass, creating a chain of
inheritance (e.g., C extends B, and B extends A).
3. Hierarchical Inheritance: Multiple classes inherit from a single superclass (e.g., B
extends A, and C also extends A).
• Note: Java does not support Multiple Inheritance with classes (a class cannot extend
multiple classes). This is to avoid the "Diamond Problem." However, multiple
inheritance of type can be achieved using interfaces.
### 2. Encapsulation
Encapsulation is the practice of bundling the data (fields) and the methods that operate on
that data into a single unit, i.e., a class. It also involves restricting direct access to an object's
data, which is known as data hiding.
This is typically achieved by making the fields private and providing public methods (called
getters and setters) to access and modify their values.
Example:
OOPs Notes
Java
class Person {
private String name; // Data is hidden
// Public getter to access the data
public String getName() {
return name;
// Public setter to modify the data
public void setName(String newName) {
this.name = newName;
### 3. Abstraction
Abstraction means hiding complex implementation details and showing only the essential
features of the object. It focuses on what an object does rather than how it does it.
In Java, abstraction is achieved using Abstract Classes and Interfaces.
• Abstract Class: A class that cannot be instantiated and may contain abstract methods
(methods without a body). A subclass must implement these abstract methods.
• Interface: A completely abstract blueprint that can only contain abstract methods
(and default/static methods). A class implements an interface, providing the body for
its methods.
### 4. Polymorphism
Polymorphism (from Greek, meaning "many forms") is the ability of an object to take on
many forms. In programming, it means a single action can be performed in different ways.
Types of Polymorphism:
OOPs Notes
1. Compile-Time Polymorphism (Static) This is resolved during compilation. The
primary example is Method Overloading.
o Method Overloading: This occurs when two or more methods in the same
class have the same name but different parameters (different number, type,
or order of parameters).
Example:
Java
class Adder {
int add(int a, int b) {
return a + b;
int add(int a, int b, int c) {
return a + b + c;
// The call obj.add(2,3) or obj.add(2,3,4) is decided at compile time.
2. Runtime Polymorphism (Dynamic) This is resolved at runtime. The primary example
is Method Overriding.
o Method Overriding: This occurs when a subclass provides a specific
implementation for a method that is already defined in its superclass. The
method signature (name, parameters) must be the same.
Example:
Java
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
class Dog extends Animal {
OOPs Notes
@Override // Annotation to indicate overriding
void makeSound() {
System.out.println("Dog barks");
// Animal myDog = new Dog();
// myDog.makeSound(); // Prints "Dog barks". This is decided at runtime.
## Core Java Concepts
### Constructor
A Constructor is a special method that is automatically called when an object of a class is
created. It is used to initialize the object's state. It has the same name as the class and no
return type.
1. Default Constructor: A no-argument constructor that the compiler provides if you
don't define any.
2. No-Argument Constructor: A constructor you define that takes no parameters.
3. Parameterized Constructor: A constructor that accepts parameters to initialize fields.
4. Copy Constructor: While Java doesn't have a built-in copy constructor like C++, you
can create one that takes an object of the same class as a parameter to copy its
values.
Example:
Java
class Car {
String model;
// Parameterized constructor
Car(String model) {
this.model = model;
}
OOPs Notes
// Car myCar = new Car("Tesla"); // Calls the constructor
### this Keyword
The this keyword is a reference to the current object instance. Its main uses are:
1. To distinguish between instance variables and local parameters with the same name.
2. To invoke a constructor from another overloaded constructor (this(...)).
3. To pass the current object as an argument to another method.
Example:
Java
class Box {
int width;
Box(int width) {
// this.width is the instance variable
// width is the local parameter
this.width = width;
### super Keyword
The super keyword is a reference to the superclass (parent) object. Its main uses are:
1. To call the superclass's constructor from the subclass's constructor (super(...)). This
must be the first line.
2. To call a superclass's method that has been overridden in the subclass
(super.methodName()).
### final Keyword
The final keyword is used to apply restrictions.
1. final variable: Creates a constant. Its value cannot be changed.
2. final method: Prevents the method from being overridden by a subclass.
OOPs Notes
3. final class: Prevents the class from being inherited (extended).
### static Keyword
The static keyword is used for memory management. It indicates that a member belongs to
the class itself, rather than to any individual object instance.
1. static variable: A single copy of this variable is shared among all objects of the class.
2. static method: Can be called without creating an object of the class
(ClassName.methodName()). It can only access static data.
## Abstract Class vs. Interface
Feature Abstract Class Interface
To achieve partial abstraction and To achieve full abstraction and define a
Purpose
share common code. contract.
Can have both abstract and non- Can only have abstract methods (and
Methods
abstract (concrete) methods. default/static methods in Java 8+).
Can have final, non-final, static, and
Variables Variables are public static final by default.
non-static variables.
A class can extend only one abstract A class can implement multiple
Inheritance
class. interfaces.
Has a constructor (called when a
Constructor Does not have a constructor.
subclass is instantiated).
In Java, access specifiers (or access modifiers) are keywords that set the visibility and
accessibility of classes, methods, and variables. They are a core part of encapsulation.
There are four access specifiers in Java, listed here from most to least restrictive.
## Summary Table
This table gives a quick overview of where members with each specifier can be accessed.
OOPs Notes
Modifier Same Class Same Package Subclass (Different Package) World (Different Package)
private
default
protected
public
Export to Sheets
## 1. private
The most restrictive access level.
• Visibility: Members declared as private are only accessible within the same class
they are declared in.
• Analogy: It's like a personal diary. Only you (the class itself) can access its contents.
No one else can see it—not even child classes.
• Use Case: This is the standard for class fields (variables) to enforce encapsulation.
You then provide public getter and setter methods to control access.
Example:
Java
class Account {
private double balance; // Only Account methods can access this directly
public void deposit(double amount) {
if (amount > 0) {
this.balance += amount; // The class can access its own private member
## 2. default (Package-Private)
OOPs Notes
This is the access level you get if you don't specify any modifier.
• Visibility: Members are accessible only to classes within the same package.
• Analogy: It's like a neighborhood bulletin board. Only the residents of your
neighborhood (the package) can see the notices. People from other neighborhoods
(different packages), even if they are related (subclasses), cannot see it.
• Use Case: Useful for helper classes or methods that should only be used by other
classes in the same functional group or module.
Example:
Java
// In package 'com.bank'
class BankHelper {
// No keyword, so it's default access
void performAudit() {
System.out.println("Performing audit...");
// Another class in the same package 'com.bank'
public class Bank {
public void runDailyTasks() {
BankHelper helper = new BankHelper();
helper.performAudit(); // This is allowed
## 3. protected
A mix of package-private and public access for subclasses.
• Visibility: Members are accessible within the same package AND by subclasses in
different packages.
OOPs Notes
• Analogy: It's like family traditions. Your immediate family (same package) knows
them, and your children who move away to a new neighborhood (subclasses in a
different package) also inherit and know those traditions. Strangers (unrelated
classes in other packages) do not.
• Use Case: Designed specifically for inheritance, allowing a parent class to expose
certain methods or variables only to its children for them to use or override.
Example:
Java
// In package 'com.vehicle'
public class Vehicle {
protected String engineType = "Generic";
// In another package 'com.cars'
import com.vehicle.Vehicle;
public class Car extends Vehicle {
public void showEngine() {
// Allowed because Car is a subclass of Vehicle
System.out.println("Engine: " + this.engineType);
## 4. public
The least restrictive access level.
• Visibility: Members are accessible from anywhere, inside or outside the package.
• Analogy: It's like a public billboard on a highway. Anyone and everyone, from any
class in any package, can see it.
• Use Case: Used for the main application programming interface (API). The methods
and classes you want other developers to use are typically made public. The main
method, for example, must always be public.
Example:
OOPs Notes
Java
public class Calculator {
// This method can be called from anywhere
public int add(int a, int b) {
return a + b;