UNIT 2: OBJECT-ORIENTED PROGRAMMING CONCEPTS - I
2.1. Introduction to Object-Oriented Programming (OOP)
-
Paradigm Shift: Moves from procedural (focus on functions/logic) to modeling software as collections of objects that interact.
-
Core Principles (Pillars of OOP):
-
Abstraction: Hiding implementation details, showing only essential features.
-
Encapsulation: Bundling data (variables) and methods (functions) into a single unit (class) and restricting direct access.
-
Inheritance: Creating new classes (subclasses) from existing ones (superclasses) to promote code reuse.
-
Polymorphism: Ability of an object to take many forms. Allows one interface to be used for different underlying forms (data types).
-
-
Objects vs. Classes:
| Class | Object | | :--- | :--- | | Logical template/blueprint. | Physical/real instance created from a class. | | Defines what attributes and behaviors exist. | Holds actual data in its attributes. | | Created once. | Multiple objects can be created from one class. | | Example:
Car(with fields: color, model). | Example:myCar = new Car();| -
Real-World Modeling:
-
Noun Identification → Objects/Classes (e.g.,
Student,Account). -
Verb Identification → Behaviors/Methods (e.g.,
deposit(),calculateGrade()). -
Adjective Identification → Attributes/Fields (e.g.,
balance,name).
-
[!TIP] Common Pitfall: Confusing a class (blueprint) with an object (actual house built from the blueprint).
2.2. Classes and Objects
-
Class Definition: Use the
classkeyword.class ClassName { // Fields (instance variables) dataType variableName; // Methods returnType methodName(parameters) { ... } // Constructors ClassName() { ... } } -
Object Instantiation:
-
Declaration:
ClassName objectName;(Creates a reference variable on the stack). -
Instantiation:
objectName = new ClassName();(newallocates memory on the heap for the object and returns its address/reference). -
Combined:
ClassName objectName = new ClassName();
-
-
Memory Allocation:
-
Stack: Stores primitive local variables and reference variables to objects.
-
Heap: Stores the actual object instances (their fields).
-
objectName(stack) → holds address → points to →{fields, methods}(heap).
-
[!TIP] Exam Focus: Be prepared to draw a simple stack-heap diagram showing a reference variable pointing to an object on the heap.
2.3. Methods
-
Method Signature:
returnType methodName(ParameterList). The signature consists of the method name and the types/order of parameters. Return type is not part of the signature for overloading. -
Method Body: Contains executable statements.
-
Calling: Use the dot operator (
.) on an object reference:objectName.methodName(arguments);. -
returnStatement:-
For non-
voidmethods:return expression;(must match return type). -
For
voidmethods:return;(optional, used to exit early).
-
-
Method Overloading:
-
Same method name, different parameter lists (type, number, or order).
-
Occurs within the same class.
-
Compile-Time Polymorphism (Static Binding). JVM decides which method to call at compile time based on the reference type and arguments.
-
Purpose: Provide multiple ways to perform a similar operation.
-
[!TIP] Common Pitfall: Overloading cannot be based on different return types alone.
2.4. Constructors
-
Purpose: Special method called automatically when an object is created (
new). Used for initialization. -
Rules:
-
Same name as the class.
-
No return type (not even
void).
-
-
Default Constructor: Provided by the compiler only if no other constructor is defined. It initializes numeric fields to 0,
charto ``,booleantofalse, and object references tonull. -
Parameterized Constructor: Accepts arguments to initialize fields with specific values.
-
thisKeyword:-
this.variableName: Refers to the current object's instance variable (resolves name conflict with parameters). -
this(arguments): Calls another constructor in the same class (Constructor Chaining). Must be the first statement.
-
-
Constructor Overloading: Having multiple constructors with different parameter lists.
[!TIP] Key Difference: Constructor name = Class name, no return type. Method has a return type (or
void).
2.5. Access Modifiers and Encapsulation
-
Access Modifiers:
| Modifier | Same Class | Same Package | Subclass (diff pkg) | Everywhere | | :--- | :---: | :---: | :---: | :---: | |
private| ✅ | ❌ | ❌ | ❌ | | default (no modifier) | ✅ | ✅ | ❌ | ❌ | |protected| ✅ | ✅ | ✅ | ❌ | |public| ✅ | ✅ | ✅ | ✅ | -
Encapsulation:
-
Declare instance variables as
private. -
Provide public getter/setter methods for controlled access.
-
-
Getters (Accessors):
public dataType getVariableName() { return variableName; } -
Setters (Mutators):
public void setVariableName(dataType value) { this.variableName = value; }(Can include validation). -
JavaBean Convention: Getter/setter names follow
getXxx()/setXxx()pattern for propertyxxx.
[!TIP] Why Encapsulate? Prevents invalid data, allows internal implementation changes without affecting client code, enables read-only/write-only fields.
2.6. Static Keyword
-
Static Variables (
staticfields):-
Belong to the class, not individual objects.
-
Shared among all instances of the class.
-
Loaded when class is loaded into memory.
-
Accessed via
ClassName.variableName(recommended) orobjectName.variableName.
-
-
Static Methods (
staticmethods):-
Belong to the class.
-
Can be called using
ClassName.methodName(). -
Cannot directly access instance (non-static) variables/methods. Can only access other static members.
-
main()method ispublic static void main(String[] args).
-
-
Static Block:
static { ... }. Executed once when the class is loaded. Used for static initialization. -
static final: Constants (e.g.,public static final double PI = 3.14;). Convention:UPPER_SNAKE_CASE.
[!TIP] Common Pitfall: A static method cannot use
thisorsuperbecause there is no current instance.
2.7. Inheritance
-
Concept: "is-a" relationship. Subclass inherits fields and methods from Superclass.
-
Keyword:
class Subclass extends Superclass { ... } -
Single Inheritance: A class can extend only one class directly.
-
Inheritance of Members:
-
publicandprotectedmembers are inherited. -
Default (package-private) members are inherited only if in same package.
-
privatemembers are not directly accessible in subclass (but are inherited; accessible via public/protected methods of superclass).
-
-
Method Overriding:
-
Redefining an inherited method in the subclass with exact same signature (name, parameters, return type).
-
Runtime Polymorphism (Dynamic Binding). JVM decides which method to call at runtime based on the actual object type.
-
Use
@Overrideannotation (recommended) – compiler checks for correct override.
-
-
superKeyword:-
super(): Calls the superclass constructor. Must be the first statement in subclass constructor. If not written, compiler insertssuper();. -
super.methodName(): Calls the overridden superclass method from the subclass. -
super.variableName: Accesses the superclass's hidden field.
-
[!TIP] Constructor Chaining:
subclass()→super()→superclass().
2.8. Polymorphism
-
Two Types:
-
Compile-Time Polymorphism (Static): Achieved by Method Overloading. Resolved at compile time.
-
Runtime Polymorphism (Dynamic): Achieved by Method Overriding and Dynamic Method Dispatch. Resolved at runtime.
-
-
Dynamic Method Dispatch:
Animal a = new Dog(); // Upcasting (implicit) a.makeSound(); // Calls Dog's makeSound() at runtime.- The method call is resolved based on the actual object (
Dog), not the reference type (Animal).
- The method call is resolved based on the actual object (
-
Upcasting: Assigning a subclass object to a superclass reference. Implicit and safe.
Superclass ref = new Subclass(); -
Downcasting: Assigning a superclass reference (that points to a subclass object) back to a subclass reference. Explicit and risky. Requires
instanceofcheck.if (a instanceof Dog) { Dog d = (Dog) a; // Downcasting }
[!TIP] Key Rule: Overridden methods are called based on the actual object's class, not the reference variable's type.
2.9. Abstract Classes and Methods
-
Abstract Class:
-
Declared with
abstractkeyword. -
Cannot be instantiated (
new AbstractClass()is illegal). -
May contain abstract methods (without body) and concrete methods (with body).
-
Can have fields, constructors, static methods, etc.
-
Purpose: Provide a common template for subclasses.
-
-
Abstract Method:
-
Declared without implementation:
abstract returnType methodName(parameters); -
Ends with a semicolon (
;). -
Must be implemented (overridden) by the first concrete subclass.
-
The containing class must be
abstract.
-
-
Concrete Class: A class that is not abstract and can be instantiated.
[!TIP] Analogy: An abstract class
Shapewith an abstract methodarea(). Concrete subclassesCircle,Rectanglemust provide their ownarea()implementation.
2.10. Interfaces
-
Interface: A contract of methods that a class agrees to implement. Pre-Java 8, it was a pure abstract type.
-
Declaration:
interface InterfaceName { ... } -
Implicit Modifiers (pre-Java 8):
-
Methods are
public abstract. -
Variables are
public static final(constants).
-
-
Implementation:
class ClassName implements Interface1, Interface2 { ... }(A class can implement multiple interfaces). -
Purpose: Achieve multiple inheritance of type. Define a role (e.g.,
Runnable,Serializable). -
Interface vs. Abstract Class:
| Interface | Abstract Class | | :--- | :--- | | Multiple inheritance allowed. | Single inheritance only (
extends). | | All methods abstract (pre-Java 8). | Can have both abstract & concrete methods. | | Onlypublic static finalvariables. | Can have any access modifiers for variables. | | No constructors. | Can have constructors (called viasuper). | | Slower (method lookup via indirection). | Faster (direct method call). | -
Java 8+ Features:
-
Default Methods:
default returnType methodName() { ... }. Provide a default implementation in an interface. Allows adding methods to interfaces without breaking existing implementations. -
Static Methods:
static returnType methodName() { ... }. Belong to the interface class.
-
2.11. final Keyword
-
finalclass: Cannot be subclassed (e.g.,String,Math).final class MyFinalClass { ... } -
finalmethod: Cannot be overridden by subclasses.final void myMethod() { ... } -
finalvariable: Value cannot be changed after initialization (constant).-
For primitives: The value is constant.
-
For reference variables: The reference cannot point to another object, but the object's state can change if the object is mutable.
final int x = 10; // x = 11; // Compile Error final List<String> list = new ArrayList<>(); list.add("a"); // OK (object state changes) list = new ArrayList<>(); // Compile Error (reference change) -
[!TIP] Use Case:
finalfor security, immutable design, and performance (JIT optimization).
2.12. Inner Classes (Nested Classes)
-
Member Inner Class:
-
Defined at member level inside another class.
-
Has access to all members (including private) of the outer class.
-
Requires an instance of the outer class to be instantiated:
Outer outer = new Outer(); Outer.Inner inner = outer.new Inner();
-
-
Static Nested Class:
-
Declared
staticinside another class. -
Cannot access instance members of the outer class directly.
-
Can be instantiated without an outer class instance:
Outer.StaticNested nested = new Outer.StaticNested();
-
-
Local Inner Class:
-
Defined within a method or block (local scope).
-
Can access final or effectively final local variables of the enclosing method.
-
-
Anonymous Inner Class:
-
One-time, unnamed class that extends a class or implements an interface.
-
Syntax:
new Interface/Class() { ... } -
Commonly used for event listeners, callbacks, or simple one-off implementations.
-
[!TIP] When to Use: Use inner classes when the inner class is logically part of the outer class and needs intimate access to its state. Use static nested classes when the nested class doesn't need outer instance reference.
2.13. Object Class (java.lang.Object)
-
Root Class: Superclass of all classes in Java. If no
extendsis written, class implicitly extendsObject. -
Key Methods (inherited by every object):
-
public String toString(): Returns a string representation. Default:ClassName@HashCode. Override for meaningful output. -
public boolean equals(Object obj): Compares logical equality (content). Default: compares references (==). Override for value-based comparison (e.g.,String,Integer). -
public int hashCode(): Returns an integer hash code. Contract: Ifequals()returnstruefor two objects, theirhashCode()must be equal. -
public Class<?> getClass(): Returns the runtime class object (used for reflection). -
protected Object clone() throws CloneNotSupportedException: Creates a field-by-field copy. -
protected void finalize() throws Throwable: Called by GC before object is collected (deprecated in Java 9+).
-
[!TIP] Golden Rule: Always override
toString()andhashCode()together withequals()to maintain theequals-hashCodecontract.
2.14. Packages
-
Purpose: Group related classes/interfaces. Avoids name conflicts. Provides access protection.
-
Declaration:
package com.example.myapp;(Must be the first non-comment line in a.javafile). -
Directory Structure: Package name corresponds to folder hierarchy (
com/example/myapp/). -
Importing:
-
Single type:
import java.util.ArrayList; -
Entire package:
import java.util.*;(Not recommended for clarity). -
No import needed for classes in the same package.
-
-
Fully Qualified Name:
packageName.ClassName(e.g.,java.util.Scanner). Used when no import is present. -
Common API Packages:
-
java.lang: Automatically imported. Core classes (String,Object,Math). -
java.util: Collections framework, date/time, utility classes. -
java.io: Input/Output operations. -
java.net: Networking.
-
-
Accessibility Across Packages:
-
public: Accessible everywhere. -
protected: Accessible in subclasses (any package) and same package. -
default: Accessible only within the same package.
-
private: Not accessible outside the class.
-
[!TIP] Best Practice: Use meaningful package names (reverse domain name convention:
com.company.project.module). Avoidimport java.util.*;in production code for clarity.