Loading...
Loading...
Object-Oriented Programming ek paradigm hai jisme program ko objects ke around organize karte hain — har object mein data (fields) aur behavior (methods) hota hai.
// Basic Java Program Structure
public class HelloBCA {
// Instance variable
private String name;
// Constructor
public HelloBCA(String name) {
this.name = name;
}
// Method
public void greet() {
System.out.println("Hello, " + name + "!");
}
public static void main(String[] args) {
HelloBCA obj = new HelloBCA("BCA Student");
obj.greet(); // Hello, BCA Student!
}
}
// Class definition
public class Student {
// Fields (instance variables)
private int rollNo;
private String name;
private double gpa;
// Constructor overloading
public Student() {
this.rollNo = 0; this.name = "Unknown"; this.gpa = 0.0;
}
public Student(int rollNo, String name, double gpa) {
this.rollNo = rollNo;
this.name = name;
this.gpa = gpa;
}
// Getters and Setters (Encapsulation)
public int getRollNo() { return rollNo; }
public String getName() { return name; }
public void setGpa(double gpa) {
if (gpa >= 0 && gpa <= 10) this.gpa = gpa;
else throw new IllegalArgumentException("Invalid GPA");
}
// toString override
@Override
public String toString() {
return "Student[" + rollNo + ", " + name + ", GPA=" + gpa + "]";
}
}
// Using the class
Student s1 = new Student(101, "Alice", 8.5);
Student s2 = new Student(); // default constructor
System.out.println(s1); // Student[101, Alice, GPA=8.5]
// Base class
public class Animal {
protected String name;
protected String sound;
public Animal(String name, String sound) {
this.name = name;
this.sound = sound;
}
public void makeSound() {
System.out.println(name + " says: " + sound);
}
public void eat() {
System.out.println(name + " is eating.");
}
}
// Single Inheritance
public class Dog extends Animal {
private String breed;
public Dog(String name, String breed) {
super(name, "Woof"); // Call parent constructor
this.breed = breed;
}
// Method Overriding
@Override
public void makeSound() {
System.out.println(name + " (a " + breed + ") barks: Woof Woof!");
}
public void fetch() {
System.out.println(name + " fetches the ball!");
}
}
// Multilevel Inheritance
public class GoldenRetriever extends Dog {
public GoldenRetriever(String name) {
super(name, "Golden Retriever");
}
@Override
public void makeSound() {
System.out.println(name + " makes a gentle woof!");
}
}
// Usage
Animal a = new Animal("Cat", "Meow");
Dog d = new Dog("Buddy", "Labrador");
d.makeSound(); // Buddy (a Labrador) barks: Woof Woof!
d.eat(); // Inherited from Animal
d.fetch(); // Dog-specific method
// Runtime Polymorphism (Dynamic Dispatch)
Animal[] animals = {
new Dog("Rex", "German Shepherd"),
new Animal("Cat", "Meow"),
new GoldenRetriever("Max")
};
for (Animal animal : animals) {
animal.makeSound(); // Each calls its OWN version
}
// Rex (a German Shepherd) barks: Woof Woof!
// Cat says: Meow
// Max makes a gentle woof!
// Compile-time Polymorphism (Method Overloading)
public class Calculator {
public int add(int a, int b) { return a + b; }
public double add(double a, double b) { return a + b; }
public int add(int a, int b, int c) { return a + b + c; }
public String add(String a, String b) { return a + b; }
}
// Abstract Class — partial implementation
public abstract class Shape {
protected String color;
public Shape(String color) { this.color = color; }
// Abstract method — must be implemented by subclass
public abstract double area();
public abstract double perimeter();
// Concrete method — shared implementation
public void display() {
System.out.println("Shape: " + color +
", Area: " + area() + ", Perimeter: " + perimeter());
}
}
public class Circle extends Shape {
private double radius;
public Circle(String color, double radius) {
super(color); this.radius = radius;
}
@Override
public double area() { return Math.PI * radius * radius; }
@Override
public double perimeter() { return 2 * Math.PI * radius; }
}
// Interface — pure contract
public interface Drawable {
void draw(); // implicitly public abstract
void resize(double factor);
// Java 8+ default method
default void print() {
System.out.println("Printing: " + getClass().getSimpleName());
}
}
public interface Resizable {
void resize(double factor);
}
// Multiple interface implementation
public class Square extends Shape implements Drawable, Resizable {
private double side;
public Square(String color, double side) {
super(color); this.side = side;
}
@Override public double area() { return side * side; }
@Override public double perimeter() { return 4 * side; }
@Override public void draw() { System.out.println("Drawing Square"); }
@Override public void resize(double f) { side *= f; }
}
// Try-catch-finally
public class FileProcessor {
public void readFile(String path) {
FileReader reader = null;
try {
reader = new FileReader(path); // Checked exception
int data = reader.read();
int result = 100 / data; // ArithmeticException (unchecked)
System.out.println("Result: " + result);
} catch (FileNotFoundException e) {
System.err.println("File not found: " + e.getMessage());
} catch (ArithmeticException e) {
System.err.println("Math error: " + e.getMessage());
} catch (IOException e) {
System.err.println("IO Error: " + e.getMessage());
} finally {
// Always executes — cleanup
if (reader != null) {
try { reader.close(); } catch (IOException e) { }
}
}
}
}
// Try-with-resources (Java 7+) — auto close
public void readFileModern(String path) throws IOException {
try (FileReader reader = new FileReader(path);
BufferedReader br = new BufferedReader(reader)) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} // reader auto-closed here
}
// Custom Exception
public class InsufficientFundsException extends Exception {
private double amount;
public InsufficientFundsException(double amount) {
super("Insufficient funds. Required: " + amount);
this.amount = amount;
}
public double getAmount() { return amount; }
}
// throw and throws
public void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException(amount);
}
balance -= amount;
}
import java.util.*;
// ArrayList — dynamic array
List<String> names = new ArrayList<>();
names.add("Alice"); names.add("Bob"); names.add("Charlie");
names.remove("Bob");
System.out.println(names.get(0)); // Alice
Collections.sort(names);
// LinkedList — doubly linked list
LinkedList<Integer> ll = new LinkedList<>();
ll.addFirst(10); ll.addLast(30); ll.add(1, 20);
// HashMap — key-value, O(1) average
Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 95); scores.put("Bob", 88);
System.out.println(scores.get("Alice")); // 95
scores.getOrDefault("Charlie", 0); // 0
for (Map.Entry<String, Integer> e : scores.entrySet()) {
System.out.println(e.getKey() + ": " + e.getValue());
}
// TreeMap — sorted by key
Map<String, Integer> sorted = new TreeMap<>(scores);
// HashSet — unique elements
Set<String> unique = new HashSet<>(names);
unique.add("Alice"); // Duplicate — ignored
System.out.println(unique.size()); // no duplicates
// PriorityQueue — min-heap by default
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.add(30); pq.add(10); pq.add(20);
System.out.println(pq.poll()); // 10 (smallest)
// Stack
Deque<Integer> stack = new ArrayDeque<>();
stack.push(1); stack.push(2);
System.out.println(stack.pop()); // 2 (LIFO)
// Generic class
public class Pair<T, U> {
private T first;
private U second;
public Pair(T first, U second) {
this.first = first; this.second = second;
}
public T getFirst() { return first; }
public U getSecond() { return second; }
@Override
public String toString() {
return "(" + first + ", " + second + ")";
}
}
// Usage
Pair<String, Integer> nameAge = new Pair<>("Alice", 20);
Pair<Double, Double> point = new Pair<>(3.14, 2.71);
// Generic method
public static <T extends Comparable<T>> T max(T a, T b) {
return (a.compareTo(b) > 0) ? a : b;
}
System.out.println(max(10, 20)); // 20
System.out.println(max("abc", "xyz")); // xyz
Q: Java mein "is-a" aur "has-a" relationship kya hai? A: IS-A = Inheritance (Dog IS-A Animal). HAS-A = Composition (Car HAS-A Engine). Composition zyada flexible hai — "favor composition over inheritance."
Q: static keyword ka kya matlab hai? A: Static members class ke hote hain, object ke nahi. static method instance variables access nahi kar sakta. static block class loading pe ek baar execute hota hai.
Q: Java mein pass-by-value hai ya pass-by-reference? A: Java ALWAYS pass-by-value. Primitive types — value copy. Objects — reference ki copy (same object point hota hai, lekin reference change hone pe original nahi badlta).
Complete OOP Java notes for B.Tech IT Sem 2 — Classes, Objects, Inheritance, Polymorphism, Abstraction, Interfaces, Exception Handling, Collections, Generics with code examples.
44 pages · 2.2 MB · Updated 2026-03-11
Encapsulation (data hiding), Inheritance (IS-A relationship, code reuse), Polymorphism (one name many forms), Abstraction (hide implementation, show interface).
Abstract class: partial implementation, constructors ho sakte hain, single inheritance. Interface: pure contract (Java 8+ default methods), multiple implementation possible, all methods public.
Checked: compile time pe handle karna mandatory (IOException, SQLException). Unchecked: runtime exceptions, handle optional (NullPointerException, ArrayIndexOutOfBoundsException).
ArrayList: random access fast O(1), insertion/deletion slow O(n). LinkedList: insertion/deletion fast O(1) at known position, random access slow O(n). Most cases ArrayList better.
Diamond problem — agar do parent classes mein same method ho, child kaunsa use kare? Java interfaces se multiple inheritance hoti hai (pure contracts, no ambiguity).
Data Structures Notes — B.Tech IT Sem 2
Data Structures
Digital Electronics — Complete Notes IT Sem 1
Digital Electronics
Java Programming — Complete Notes for B.Tech IT Semester 3
Java Programming
Web Technologies — HTML, CSS, JavaScript, Node.js Complete Notes
Web Technologies
Cloud Computing Notes — B.Tech IT Sem 5
Cloud Computing
Your feedback helps us improve notes and tutorials.