JAVA OOPS LEARN!!
#1 Introduction to Java
Java is a high-level, Fully object-oriented, class-based, and platform-
independent programming language.
Developed by James Gosling at Sun Microsystems in 1995.
Write once, run anywhere (WORA) – thanks to the Java Virtual Machine
(JVM).
#4 How Java Works
🟩 Java Program Structure
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, Java!");
🔹 Breakdown of Code:
public class HelloWorld:- Every Java program must have a class.
public static void main(String[] args): Entry point of the program.
[Link](...): Prints output to the console.
✅ 1. Compile the code
Use the javac (Java Compiler) to convert the .java file into a .class file.
javac [Link]
This .class file contains bytecode (a special format, not machine code).
✅ 2. Run the code
Use the java command (Java launcher) to run the bytecode:
java HelloWorld
This runs the Java Virtual Machine (JVM), which reads the bytecode and converts it into
machine code for your OS/CPU.
✅ 3. JVM Execution
The JVM (Java Virtual Machine) loads the .class file.
It uses the Class Loader, Bytecode Verifier, and Interpreter to execute the program.
✅ JDK = Java Development Kit
It is a software development kit used to develop Java applications. It includes:
1. JVM Runs the bytecode
2. JRE Java Runtime Environment – includes JVM + libraries
#21 Class and Object Java
🟩 What is an Object in Java?
An object is a real-world entity in programming that has:
✅ Properties (State) → Variables
✅ Behaviors (Actions) → Methods (functions)
🟦 What is a Class in Java?
A class is like a blueprint or template to create objects.
It defines what properties and behaviors an object will have, but doesn’t create the
object itself.
🔄 Real-Life Analogy: Class vs Object
✴️Analogy: Car
Java Term
Concept Analogy Example
Class Car blueprint/design class Car { ... }
Object Actual car made from blueprint Car car1 = new Car();
Properties color, model, speed Variables: color, speed
Behaviors drive, brake, honk Methods: drive(), brake()
🔸 Java Code Example Based on Car:
// Class Definition (Blueprint)
public class Car {
// Properties (State)
String color;
int speed;
// Behavior (Method)
void drive() {
[Link]("The car is driving.");
void brake() {
[Link]("The car is braking.");
// Object Creation and Usage
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // Object
[Link] = "Red"; // Setting property
[Link] = 80;
[Link](); // Calling behavior
[Link]();
}
}
#34 String
🟩 What is a String in Java?
A String is a sequence of characters.
In Java, String is a class, not a primitive type.
Strings are immutable → once created, they cannot be changed.
🟦 Declaring Strings
String str1 = "Hello"; // Using string literal
String str2 = new String("Java"); // Using constructor (not common)
🟩 Common and Important String Methods in Java
Method Description Example
length() Returns length of string [Link]()
charAt(index) Returns character at given index [Link](0)
substring(start, end) Extracts substring from start to end-1 [Link](0, 4)
contains("text") Checks if string contains a sequence [Link]("Java")
equals(str2) Compares two strings (case-sensitive) [Link](str2)
toUpperCase() Converts to upper case [Link]()
toLowerCase() Converts to lower case [Link]()
trim() Removes leading and trailing spaces [Link]()
replace(old, new) Replaces characters or substrings [Link]("a", "o")
split("delimiter") Splits the string based on delimiter [Link](" ")
isEmpty() Checks if string is empty (length() == 0) [Link]()
#35 StringBuffer
🟩 What is StringBuffer in Java?
StringBuffer is a mutable sequence of characters (unlike String which is immutable).
It modifies the content without creating a new object.
It's thread-safe — meaning it is safe to use in multi-threaded programs.
🟦 Why use StringBuffer?
When you need to perform multiple modifications (append, insert, delete) on a string and
performance matters.
StringBuffer is faster than String for many updates.
🟩 Declaring a StringBuffer
StringBuffer sb = new StringBuffer(); // Empty buffer
StringBuffer sb2 = new StringBuffer("Hello"); // Initialized buffer
🟦 Important Methods of StringBuffer
Method Description Example
append(String s) Adds string to the end [Link](" World")
insert(int offset, String s) Inserts string at specified position [Link](5, " Java")
reverse() Reverses the sequence of characters [Link]()
charAt(index) Returns character at given index [Link](2)
length() Returns length of buffer [Link]()
toString() Converts buffer to string [Link]()
#37. Static Key
🟩 What is a Static Variable in Java?
Static variables are declared using the static keyword.
They are shared by all objects of the class.
Accessed via [Link] or [Link].
A static variable is a class-level variable, not tied to any specific object.
It is created only once in memory, at the time of class loading.
🟦 Declaration:
class Example {
static int count = 0; // Static variable
🟨 Real-Life Analogy:
📦 Static variable is like a common notice board in a classroom:
All students (objects) can see it and update it.
Only one copy is shared among all
#38 Static Method
🟩 What is a Static Method in Java?
A static method belongs to the class, not to any object.
It can be called without creating an object.
It is declared using the static keyword.
🟦 Syntax:
class MyClass {
static void greet() {
[Link]("Hello, Nanbaa!");
You can call it like this:
[Link](); // No object needed
✅ Can be called using class name -- [Link]()
✅ Common examples: main(), [Link](), [Link](), [Link]()
#40 Encapsulation
Encapsulation is the wrapping of data (variables) and code (methods) together into a single
unit — typically a class.
➡️It’s like placing data inside a capsule and protecting it from outside access.
Why Use Encapsulation?
✅ To protect data from direct access or modification.
✅ To make your class a black box — you can control how the data is accessed or changed.
✅ Improves security, readability, and maintainability.
🟨 Real-Life Analogy:
🧃 Imagine a juice bottle:
You can't access the juice directly (data is private).
You use the cap (methods) to open/close the bottle (access it safely).
Likewise, in Java:
Make variables private.
Provide getters and setters to control access.
🟦 How to Achieve Encapsulation in Java:
1. 🔒 Make data members private. Key – ‘private’
2. ✅ Use getter methods to read the data. Eg: getFieldName() — returns the value.
3. ✅ Use setter methods to modify the data. Eg: setFieldName(value) — sets the value.
this – Keyword
🟩 What is this in Java?
‘this ‘ is a reference variable in Java.
It refers to the current object of the class.
‘This’ refers to the current object.
Can also be used to:
o Call constructor: this()
o Call method: [Link]()
🟦 Example: Resolving Variable Conflict
class Student {
String name;
Student(String name) {
[Link] = name; // '[Link]' refers to instance variable
void show() {
[Link]("Name: " + name);
Without [Link] = name, both would refer to the parameter — not what we want!
Constructor
🟩 Constructor in Java
A constructor is a special method used to initialize objects.
It has the same name as the class and no return type (not even void).
It is automatically called when you create an object.
🟨 Types of Constructors:
✅ 1. Default Constructor
Created automatically by Java if no constructor is defined.
Used to give default values to objects.
✅ 2. Parameterized Constructor
Allows you to pass values while creating the object.
Used to initialize objects with custom values.
🟩 Inheritance in Java
Inheritance is a mechanism where one class (child/subclass) inherits the properties and
behaviors (fields and methods) of another class (parent/superclass).
👉 It promotes code reusability and supports hierarchical classification.
🟨 Syntax:
class Parent {
// Parent class members
class Child extends Parent {
// Child class inherits from Parent
📝 Key Points:
extends keyword - Used for inheritance
Parent class - Also called superclass
Child class - Also called subclass
Inheritance
🟩 1. Single Inheritance
➡️A class inherits from only one parent class.
🔷 Structure:
A (Parent)
↑
B (Child)
🟩 2. Multilevel Inheritance
➡️A class inherits from another child class, forming a chain.
🔷 Structure:
A (Grandparent)
B (Parent)
C (Child)
🟥 3. Multiple Inheritance (Not Supported in Java using classes)
🔷 What is it?
➡️A class tries to inherit from two parent classes.
🔷 Structure:
A B
\ /
\ /
🔷 Why Java Doesn’t Support This?
➡️Because of ambiguity problem called the Diamond Problem.
✅ Java’s Solution: Use Interfaces Instead
Java supports multiple inheritance using interfaces, which do not have method bodies (or use
default methods clearly). So there's no ambiguity.
learn about this() & super() Method in
Java
Method Overriding:
🟩 What is Method Overriding?
A subclass provides its own version of a method that is already defined in the superclass.
✅ Same method name, return type, and parameters
✅ Happens in inheritance
🟨 Why Override?
To change the behavior of the inherited method.
Useful in runtime polymorphism (dynamic method dispatch).
🟥 Real-Life Analogy:
🧍♂️Parent Class: Remote Control
RemoteControl has a method: pressButton() → "Default Action"
Subclass: TVRemote
Overrides pressButton() → "Turns ON the TV"
🎧 Subclass: MusicSystemRemote
Overrides pressButton() → "Plays music"
📌 When you press the button, each remote gives a different result — even though the method name
is same.
Vishual : if you have your Mobile phone, when somebody ask what mobile you have?. You
reply that your model, not your dad mobile model. Because you give first preference to your
owns.
📝 Rules for Overriding:
Rule Description
✅ Same method signature Name + parameters + return type
✅ Access modifier Can be same or more visible (e.g., protected → public)
🟦 Access Modifiers in Java
🔑 Access Modifiers define the visibility or scope of classes, methods, variables, and constructors.
🔷 1. private
Accessible only within the same class.
Used for encapsulation (like private data members).
Like Your phone lock (only you)
🔷 2. protected
Accessible in:
o Same class
o Subclasses (even in different packages)
Mostly used for inheritance purposes.
Like Family property (you and your children)
🔷 3. public
Accessible from anywhere (any class, any package).
Used for main(), API methods, etc.
Like Public park (anyone can access)
✅ Best Practices:
1. Always use the lowest access level that makes sense.
o This improves security and code encapsulation.
2. Use private for instance variable and helper methods.
3. Use public when you declare your class.
4. If methods are going to access by subclass (inheritance) only make it as protected, otherwise
declare as public.
5. Never leave access modifier empty (i.e., default) unless it's intentional.
🟦 Polymorphism
"Polymorphism" comes from the Greek words poly (many) and morph (forms).
✅ Definition:
Polymorphism in Java means the ability of a method or object to take many forms.
It allows the same method name to behave differently based on context.
🔶 Types of Polymorphism in Java:
Type Also Called As When It Happens
Compile-Time Polymorphism Method Overloading At Compile Time
Run-Time Polymorphism Method Overriding At Runtime
🟩 1. Compile-Time Polymorphism (Method Overloading)
Multiple methods with same name but different parameters in the same class.
Compiler chooses which one to call.
🟥 2. Run-Time Polymorphism (Method Overriding)
A child class overrides a method from the parent class.
Method that gets called depends on object type, not reference.
Method call is decided at runtime using dynamic method dispatch.
🧠 Analogy:
Imagine a "Remote Control" (parent class):
You point it to a TV → it turns on the TV.
You point it to a Projector → it turns on the projector.
Even though the remote looks the same, its behavior changes based on the device (child class) —
that's polymorphism.
🟦 Dynamic Method Dispatch in Java
Dynamic Method Dispatch is the process of resolving method calls at runtime, not at
compile time.
It happens when a superclass reference points to a subclass object, and a method is
overridden.
Because:
The decision of which version of the overridden method to execute is made dynamically at
runtime, based on the actual object.
🔷 Syntax Pattern:
public class Test {
public static void main(String[] args) {
Animal a; // Reference of superclass
a = new Dog(); // Upcasting
[Link](); // Dog's sound()
a = new Cat(); // Upcasting
[Link](); // Cat's sound()
🔄 What Happened?
Even though the reference a is of type Animal, the actual object is Dog or Cat.
At runtime, Java decides which class’s sound() method to execute → this is Dynamic
Method Dispatch.
The method call is resolved based on the actual object type, not the reference type.
🟦 abstract Keyword in Java
In Java, the abstract keyword is used to declare:
1. Abstract Class
2. Abstract Method
🟩 1. Abstract Class
An abstract class:
Cannot be instantiated (you cannot create its object)
Can have abstract and non-abstract (concrete) methods
Is meant to be inherited by other classes
abstract class Animal {
abstract void sound(); // abstract method
🟦 2. Abstract Method
An abstract method:
Has no body (ends with ;)
Must be overridden in the subclass
abstract class Shape {
abstract void draw(); // no body
class Circle extends Shape {
void draw() {
[Link]("Drawing Circle");
}
🧠 Real-Life Analogy:
🧱 Abstract Class: Blueprint of a building
You can’t live in a blueprint (you can't instantiate it),
but you can create actual buildings (subclasses) from it — each with different styles (method
implementations).
📝 Summary for Notes:
abstract keyword → applied to classes and methods
Abstract class = partial implementation , Cannot instantiate abstract classes
abstract method = No body; must be overridden in subclass.
Subclass -> Must override all abstract methods or itself be abstract
🟦 Interface in Java
✅ What is an Interface?
An interface is like a contract in Java.
It contains only abstract methods (by default) and constants.
-> It's used to achieve 100% abstraction and multiple inheritance in Java.
🔧 Syntax:
interface Vehicle {
void start(); // abstract method by default
int MAX_SPEED = 120; // public static final by default
🔄 Real-Life Analogy:
🧩 Think of an interface as a remote control —
You define which buttons are needed, but each device (TV, AC, Fan) implements the actual
behavior.
📌 Important Points to Remember:
interface keyword is used.
All methods are public abstract by default.
All variables are public static final.
A class uses implements to adopt an interface.
Supports multiple inheritance
Can’t create objects of interfaces
Different Ways:
🔹 class – class -> extends
When one class extends another class, it inherits the fields and methods of the parent class.
🔹 class – interface -> implements
A class implements an interface to provide behavior (method definitions) that the interface declares.
🔹 interface – interface -> extends
An interface can extend another interface to inherit its abstract methods.
🟦 final Keyword in Java
The final keyword is a non-access modifier in Java.
It is used to restrict modification — meaning once something is declared as final, it cannot be
changed.
🔷 final Can Be Applied To:
1. Variable
2. Method
3. Class
🟩 1. final Variable
Once assigned, its value cannot be changed.
final int x = 10;
x = 20; // ❌ Error: cannot assign a value to final variable
🟦 2. final Method
A final method cannot be overridden by subclasses.
class Parent {
final void show() {}
📝 Use: To prevent method modification in subclasses.
🟥 3. final Class
A final class cannot be inherited.
final class Vehicle {
void run() {}
📝 Use: To prevent further extension of a class (e.g., for security or design reasons).
✅ Summary for Notes:
final = "can’t be changed"
Variable → value fixed
Method → can’t override
Class → can’t inherit
🟥 Exception Handling in Java
✅ What is Exception Handling?
Exception Handling is a mechanism to handle runtime errors (like divide-by-zero, null pointer, file
not found) in a graceful way without crashing the program.
⚠️Exception = Unexpected Event
It interrupts the normal flow of the program.
🎯 Why Exception Handling?
To prevent abnormal termination
To give meaningful error messages
To keep the program robust and reliable
🔧 Basic Syntax using try-catch:
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
🔁 Flow of Execution:
1. Java enters the try block
2. If an exception is not thrown → catch is skipped
3. If an exception is thrown → control goes to matching catch block
Only one try, but multiple catch blocks allowed
Catch order matters — catch subclass exceptions before superclass
Only Throwable types (Exception/Error) can be thrown