UNIT 2: Object-Oriented Programming (OOP) Fundamentals
2.1 Classes and Objects: The Building Blocks
-
Class: A blueprint/template that defines the structure (fields) and behavior (methods) of objects.
- Syntax:
class ClassName { // fields, methods }
- Syntax:
-
Object: A concrete instance of a class created at runtime.
-
Instantiation:
ClassName obj = new ClassName(); -
Reference Variable:
objholds the memory address of the object, not the object itself. -
Member Access: Use dot operator
.(e.g.,obj.field,obj.method()).
-
-
Variables:
-
Instance Variables: Declared inside the class, outside methods. Each object has its own copy. Created with
new. -
Local Variables: Declared inside a method/block. Exist only during method execution.
-
-
Constructors:
-
Special method called when an object is created. Same name as class, no return type.
-
Default Constructor: Provided by compiler if no constructor is defined. Initializes fields to default values (e.g.,
0,null). -
Parameterized Constructor: Accepts arguments to initialize fields.
-
Constructor Overloading: Multiple constructors with different parameter lists.
-
thisKeyword: Refers to the current object instance. Used to:-
Resolve variable shadowing (distinguish instance variable from parameter).
-
Call another constructor in the same class (
this(...)). -
Pass the current object as a parameter.
-
-
-
Method Overloading:
-
Multiple methods in the same class with the same name but different parameters (type, number, or order).
-
Achieves compile-time polymorphism (static binding). Method call is resolved at compile time based on the reference type.
-
Rules: Must differ in parameter list. Return type and access modifier can differ but are not sufficient for overloading.
-
[!TIP] Common Pitfall: Confusing overloading (same class, different params) with overriding (superclass-subclass, same signature).
2.2 Encapsulation and Data Hiding
-
Goal: Bundle data (fields) and methods (behaviors) together, and restrict direct access to internal state.
-
Access Modifiers: Control visibility of classes, fields, and methods.
| Modifier | Class | Package | Subclass | World | |----------|-------|---------|----------|-------| |
private| ✅ | ❌ | ❌ | ❌ | | default (package-private) | ✅ | ✅ | ❌ | ❌ | |protected| ✅ | ✅ | ✅ | ❌ | |public| ✅ | ✅ | ✅ | ✅ | -
Implementation:
-
Declare fields as
private. -
Provide public
getter(accessor) andsetter(mutator) methods to controlled access. -
Add validation logic inside setters if needed.
-
-
Benefits: Prevents invalid state changes, increases flexibility (internal implementation can change without affecting clients), improves maintainability.
2.3 Inheritance: Achieving Reusability
-
Concept: A mechanism where a new class (subclass/child) acquires properties and behaviors of an existing class (superclass/parent). Promotes code reuse.
-
Syntax:
class Subclass extends Superclass { ... } -
Inheritance Chain: A subclass inherits all non-private members (fields and methods) of its direct superclass. Constructors are not inherited.
-
superKeyword: Reference to the immediate superclass.-
super(): Calls the superclass constructor. Must be the first statement in a subclass constructor. -
super.variable/super.method(): Accesses hidden superclass members (if subclass has a field/method with same name).
-
-
Types of Inheritance in Java:
-
Single: One subclass inherits from one superclass. (e.g.,
CarextendsVehicle) -
Multilevel: A chain of inheritance. (e.g.,
CarextendsVehicleextendsObject) -
Hierarchical: Multiple subclasses inherit from one superclass.
-
Multiple: NOT SUPPORTED for classes (a class cannot extend more than one class). Achieved via interfaces.
-
Hybrid: Combination of above.
-
[!TIP] Constructor Execution Order: When creating a subclass object, superclass constructor executes first (top of hierarchy down to
Object), then subclass constructor.
2.4 Polymorphism: Many Forms
-
Method Overriding:
-
Redefining a non-static, non-final, non-private method of the superclass in the subclass.
-
Rules:
-
Same method signature (name + parameter types).
-
Return type must be the same or a covariant subtype (Java 5+).
-
Access modifier cannot be more restrictive.
-
Cannot throw new or broader checked exceptions.
-
-
@OverrideAnnotation: Best practice. Informs compiler to check for overriding rules. Prevents errors (e.g., due to typo in method name). -
Runtime Polymorphism (Dynamic Method Dispatch): The JVM decides at runtime which overridden method to call based on the actual object type, not the reference type.
-
-
Applying Polymorphism:
-
A superclass reference variable can hold an object of any of its subclasses.
-
Example:
Animal a = new Dog(); // Upcasting (implicit) a.makeSound(); // Calls Dog's makeSound() at runtime -
Enables writing generic code that works with objects of multiple related types.
-
2.5 Static and Final Keywords
-
staticMembers:-
staticVariables (Class Variables): Belong to the class, not individual objects. Shared among all instances. Loaded when class is loaded. -
staticMethods (Class Methods): Can be called without an object (ClassName.method()). Cannot usethisorsuper. Can only directly accessstaticmembers. -
Static Block:
static { ... }. Executed once when the class is first loaded. Used for static initializations.
-
-
finalKeyword: "Cannot be changed."-
finalVariable: A constant. Must be initialized exactly once (at declaration or in constructor). Primitive: value cannot change. Reference: reference cannot point to another object (but object state can change if mutable). -
finalMethod: Cannot be overridden by subclasses. -
finalClass: Cannot be subclassed (inherited). (e.g.,String,Integer).
-
2.6 Practical Implementation & Common Lab Patterns
-
Creating a Simple Hierarchy:
-
Example:
Person(superclass) ->Student&Employee(subclasses). -
Constructor Chaining: Subclass constructor should call
super(...)to initialize inherited fields. If omitted, compiler insertssuper().
-
-
instanceofOperator:-
Purpose: Check if an object is an instance of a specific class or interface at runtime.
-
Syntax:
obj instanceof ClassName→ returnsboolean. -
Use Case: Safe downcasting.
if (obj instanceof Student) { Student s = (Student) obj; // Safe downcast }
-
-
Type Casting:
-
Upcasting: Subclass object → Superclass reference. Implicit and safe.
Animal a = new Dog(); // No cast needed -
Downcasting: Superclass reference → Subclass reference. Explicit and risky. Throws
ClassCastExceptionif the actual object is not of the target subclass.Animal a = new Dog(); Dog d = (Dog) a; // Explicit cast, safe here
-
-
Common Pitfalls & Debugging:
-
NullPointerException: Calling a method/accessing field on anullreference. -
Shadowing vs Overriding:
-
Shadowing: Subclass declares a field with the same name as a superclass field. Accessed via
super.field. -
Overriding: Subclass provides a new implementation for a method. Invoked via dynamic dispatch.
-
-
Constructor Chain Failure: If superclass has no default constructor and subclass constructor doesn't explicitly call
super(...), compilation error. -
ClassCastException: Attempting invalid downcasting. Always useinstanceofto check before downcasting.
-
[!TIP] Golden Rule for Casting: Upcast freely, downcast with
instanceofcheck.