4.1 Introduction to Object-Oriented Programming (OOP)
Paradigm Shift: Transition from procedural programming (focus on functions/sequence of steps) to object-oriented programming (focus on objects that combine data and behavior). OOP models real-world entities as software objects.
Four Pillars of OOP:
-
Abstraction: Hiding implementation details, showing only essential features. Achieved via abstract classes/interfaces.
-
Encapsulation: Bundling data (variables) and code (methods) into a single unit (class) and restricting direct access via
privatemodifiers. -
Inheritance: Acquiring properties and behaviors from an existing class (superclass) using
extends. Promotes code reuse. -
Polymorphism: "Many forms." Allows objects to take multiple forms—via method overloading (compile-time) and overriding (runtime).
Advantages of OOP:
-
Modularity: Code organized into classes.
-
Reusability: Inheritance and composition reduce redundancy.
-
Maintainability: Changes localized to classes.
-
Scalability: Easier to design large systems.
-
Data Security: Encapsulation protects data.
Real-World Modeling:
-
Object: A concrete instance (e.g., a specific
Car). -
Class: Blueprint/template for objects (e.g.,
Carclass withcolor,speedfields). -
Relationships: Association, aggregation, composition, inheritance.
4.2 Classes and Objects
Class: A template/blueprint defining attributes (instance variables) and behaviors (methods).
class Student {
String name; // Instance variable
int rollNo;
void study() { // Method
System.out.println("Studying...");
}
}
Object: A runtime instance of a class. Created using new keyword.
Student s1 = new Student(); // Object creation
s1.name = "Rahul"; // Access via dot operator
s1.study();
-
Reference Variable:
s1stores memory address (heap) of the object. -
Memory Allocation:
-
Stack: Stores reference variables and primitive local variables.
-
Heap: Stores actual object data.
-
Key Points:
-
Class declaration:
class ClassName { ... } -
Objects are independent; each has its own copy of instance variables.
-
Dot operator (
.) accesses members:object.member.
4.3 Constructors
Definition: Special method invoked at object creation to initialize state. Same name as class, no return type.
Types:
-
Default Constructor: Implicitly provided by compiler if no constructor defined. Initializes with default values (
0,null,false). -
Parameterized Constructor: Accepts arguments to initialize fields explicitly.
Constructor Overloading: Multiple constructors with different parameter lists (type/number/order).
class Box {
double length;
// Constructor 1
Box() { length = 1.0; }
// Constructor 2 (overloaded)
Box(double l) { length = l; }
}
this Keyword:
-
Refers to current object's instance variables (resolves name conflicts).
-
Calls another constructor in same class:
this(arguments); must be first statement.
Box(double l, double w) {
this(l); // Calls Box(double)
this.width = w;
}
Constructor vs. Method:
| Constructor | Method |
|---|---|
| Same name as class | Any valid identifier |
| No return type | Must have return type |
Called implicitly on new |
Called explicitly |
| Used for initialization | Performs actions |
4.4 Methods
Method Declaration: returnType methodName(parameterList) { ... }
public int add(int a, int b) {
return a + b;
}
Method Overloading:
-
Same method name, different parameters (type, number, or order).
-
Compile-time Polymorphism: JVM decides at compile time which method to call.
-
Rules:
-
Must differ in parameter list.
-
Return type can differ (not sufficient alone).
-
Access modifier can vary.
-
void print(int x) { ... }
void print(String s) { ... } // Overloaded
4.5 Access Modifiers (Access Specifiers)
Controls visibility of classes, variables, and methods.
| Modifier | Class | Package | Subclass | World |
|---|---|---|---|---|
private |
✓ | ✗ | ✗ | ✗ |
| default (no modifier) | ✓ | ✓ | ✗ | ✗ |
protected |
✓ | ✓ | ✓ | ✗ |
public |
✓ | ✓ | ✓ | ✓ |
Application:
-
Top-level classes: Only
publicor default. -
Members (variables/methods): All four modifiers.
-
private: Most restrictive; used for data hiding. -
protected: Accessible to subclasses even in different packages. -
public: Unrestricted access.
4.6 Encapsulation & Data Hiding
Concept: Bundling data and methods together, while restricting direct data access.
Implementation:
-
Declare instance variables
private. -
Provide public
getter(accessor) andsetter(mutator) methods.
class Employee {
private double salary;
public double getSalary() { return salary; }
public void setSalary(double s) {
if(s >= 0) salary = s; // Validation
}
}
Advantages:
-
Control: Validate data in setters.
-
Flexibility: Internal implementation can change without affecting users.
-
Security: Prevents unauthorized modification.
-
Reusability: Encapsulated code is modular.
4.7 Static Keyword
Static Variables (static):
-
Belong to class, not individual objects.
-
Single copy shared among all instances.
-
Stored in method area (permgen/metaspace).
class Counter {
static int count = 0; // Shared
Counter() { count++; }
}
Static Methods:
-
Called using class name:
ClassName.method(). -
Can directly access only
staticmembers. -
Cannot use
thisorsuper. -
mainmethod isstatic(JVM calls it without an object).
static void printCount() {
System.out.println(count); // OK
// System.out.println(this); // Error
}
Static Block: Executed once when class is loaded.
static {
// Initialize static variables
count = 100;
}
4.8 Inheritance
Concept: A child class (subclass) acquires fields/methods from a parent class (superclass). Uses extends keyword.
Types in Java:
-
Single: One subclass extends one superclass.
-
Multilevel: Chain of inheritance (A → B → C).
-
Hierarchical: Multiple subclasses extend one superclass.
-
Multiple: Not supported for classes (causes diamond problem). Achieved via interfaces.
super Keyword:
-
Calls superclass constructor:
super(arguments); must be first statement in subclass constructor. -
Accesses hidden superclass members:
super.variableorsuper.method().
class Animal {
Animal() { ... }
}
class Dog extends Animal {
Dog() {
super(); // Calls Animal()
}
}
Constructor Chaining: In inheritance, constructor of subclass implicitly calls super() (no-arg) if not specified. If superclass has no default constructor, subclass must explicitly call super(args).
Object Class: Root of all Java classes. Every class implicitly extends Object. Provides:
-
toString(): Returns string representation. -
equals(): Compares object equality. -
hashCode(): Returns hash code.
4.9 Polymorphism
Definition: Ability of an object to take many forms.
Compile-Time Polymorphism (Static Binding):
- Method Overloading: Multiple methods with same name but different parameters in the same class. Resolved at compile time.
Runtime Polymorphism (Dynamic Binding):
-
Method Overriding: Subclass provides a specific implementation for a method already defined in superclass.
-
Rules:
-
Same method signature (name + parameters).
-
@Overrideannotation (optional but recommended). -
Access modifier cannot be more restrictive (e.g.,
publicin superclass, subclass can bepublicbut notprivate). -
Return type can be covariant (subtype).
-
staticmethods cannot be overridden (they are hidden). -
finalmethods cannot be overridden.
-
@Override public void sound() { ... } // Overriding -
-
Dynamic Method Dispatch: Superclass reference variable can refer to subclass object and call overridden method at runtime.
Animal a = new Dog(); a.sound(); // Calls Dog's sound() at runtime -
Upcasting: Assigning subclass object to superclass reference:
Animal a = new Dog();(implicit, safe).
Overloading vs. Overriding:
| Feature | Overloading | Overriding |
|---|---|---|
| Scope | Same class | Subclass |
| Parameters | Must differ | Must be identical |
| Return Type | Can differ | Must be same or covariant |
| Access Modifier | Can change | Cannot be more restrictive |
static methods |
Can overload | Cannot override (hidden) |
| Binding Time | Compile-time | Runtime |
4.10 Abstract Classes and Methods
Abstract Class:
-
Declared with
abstractkeyword. -
May contain abstract methods (no body) and concrete methods (with body).
-
Cannot be instantiated directly.
-
Used as a base for subclasses to provide common functionality.
abstract class Shape {
abstract void draw(); // Abstract method
void fill() { ... } // Concrete method
}
Abstract Method:
-
Declared without implementation:
abstract void methodName(); -
Must be implemented by the first concrete subclass.
-
Subclass remains abstract if it doesn't implement all abstract methods.
When to Use:
-
Share common code among related classes (template pattern).
-
Declare methods that subclasses must implement.
-
Partial implementation.
Abstract vs. Concrete Class:
| Abstract Class | Concrete Class |
|---|---|
| May have abstract methods | No abstract methods |
| Cannot instantiate | Can instantiate |
| May have constructors | May have constructors |
| Can extend another class | Can extend another class |
4.11 Interfaces
Definition: A contract of abstract methods (and more) that a class agrees to implement. Declared with interface keyword.
Declaring & Implementing:
interface Drawable {
void draw(); // Implicitly: public abstract
}
class Circle implements Drawable {
public void draw() { ... } // Must implement
}
Features:
-
All methods are
public abstractby default (pre-Java 8). -
All variables are
public static final(constants). -
Multiple Inheritance: A class can implement multiple interfaces.
-
Interfaces cannot be instantiated.
-
A class can extend one class and implement multiple interfaces.
Interface vs. Abstract Class:
| Feature | Interface | Abstract Class |
|---|---|---|
| Methods (pre-Java 8) | All abstract | Can have concrete |
| Variables | public static final |
Any access modifier |
| Multiple Inheritance | Yes (via interfaces) | No (single inheritance) |
| Constructors | No | Yes |
| State (instance variables) | No (only constants) | Yes |
main method |
Can have static |
Can have main |
Java 8+ Evolution:
-
Default Methods:
default void method() { ... }(provides default implementation; classes can override). -
Static Methods:
static void method() { ... }(called via interface name). -
Private Methods (Java 9+):
private void helper() { ... }(shared code between default/static methods).
4.12 The final Keyword
final Variable: Constant; cannot be reassigned after initialization.
final double PI = 3.14; // PI cannot change
final Method: Cannot be overridden by subclasses.
final void display() { ... } // Subclasses cannot override
final Class: Cannot be subclassed (inherited).
final class MathUtils { ... } // No class can extend MathUtils
Common Use: Security, immutable classes (e.g., String is final), preventing inheritance for design reasons.
4.13 Practical Implementation & Common Pitfalls
Complete Class Example:
public class Student {
// 1. Private fields (encapsulation)
private String name;
private int age;
// 2. Constructors
public Student() { } // Default
public Student(String n, int a) {
this.name = n; // 'this' to disambiguate
this.age = a;
}
// 3. Getters/Setters
public String getName() { return name; }
public void setName(String name) { this.name = name; }
// 4. Business method
public void display() {
System.out.println(name + " " + age);
}
}
Inheritance & super:
class Person {
String name;
Person(String n) { name = n; }
}
class Employee extends Person {
int id;
Employee(String n, int id) {
super(n); // Must call superclass constructor
this.id = id;
}
}
Runtime Polymorphism:
Animal a = new Dog(); // Upcasting
a.sound(); // Calls Dog.sound() at runtime
Choosing Abstract Class vs. Interface:
-
Use abstract class when: sharing common code/state among closely related classes, needing constructors, or having non-public members.
-
Use interface when: defining a contract for unrelated classes, needing multiple inheritance of type, or expecting frequent API changes (default methods allow adding methods without breaking implementations).
Common Pitfalls:
-
Forgetting
super(): If superclass has no default constructor, subclass must explicitly callsuper(args). -
Incorrect Overriding: Changing method signature (parameters), return type incompatible, or making method more restrictive.
-
Static Context Error: Accessing non-static members (variables/methods) from
staticcontext (e.g.,mainmethod).static void main(String[] args) { // obj.instanceVar; // Error if obj not declared static } -
Misunderstanding
static:staticmethods cannot be overridden (only hidden).staticvariables are shared—avoid mutable static state unless intentional. -
Default Access: Members with default (no modifier) are package-private—subclasses in other packages cannot access them.
-
finalMisuse: Declaring classfinalprevents inheritance; methodfinalprevents overriding.
[!TIP]
- Constructor Chaining: In inheritance, superclass constructor always executes first. Use
super()to control which constructor.
- Upcasting is safe; downcasting requires explicit cast and
instanceofcheck to avoidClassCastException.
- Interface Variables are
public static finalby default—treat them as constants.