Chapter 10: Object-Oriented Programming (OOP) Concepts

This chapter builds on everything learned so far (variables, methods, control flow, etc.). We will proceed extremely slowly, step by step, examining each concept with multiple complete, runnable code examples (copy-paste into IntelliJ or Eclipse and run immediately). Each section includes detailed breakdowns, real-world analogies, tables for quick reference, common mistakes with fixes, and structured explanations. By the end, you will create your first full OOP programs confidently.

1. Why OOP? (The Big Picture)

Procedural code (Chapters 1–9) treats data and functions separately — like a list of numbers and separate math functions. OOP bundles data and behavior together into objects, mimicking real life.

Four Pillars of OOP (introduced here, detailed later):

  • Encapsulation: Data hiding (private variables, public methods).
  • Inheritance: Reuse code (child classes extend parents).
  • Polymorphism: Same method, different behaviors.
  • Abstraction: Hide complexity.

Real-world analogy: A Car is a class (blueprint: engine, wheels, color, drive() method). Each vehicle (object) is an instance: myCar = new Car(“red”); yourCar = new Car(“blue”).

2. Classes and Objects (The Foundation)

A class is a blueprint/template defining properties (fields/variables) and behaviors (methods). An object is an instance of a class — created with new.

Syntax for Class Definition:

Java

Complete Example 1: Simple Class and Object Create two files: Car.java (class) and Main.java (to test).

Car.java:

Java

Main.java (test it):

Java

Output:

text

Step-by-Step Breakdown:

  1. Car car1 = new Car(); → Allocates memory for object, calls constructor (defaults fields to null/0).
  2. car1.brand = “Toyota”; → Sets field (direct access — insecure, fixed later).
  3. car1.displayInfo(); → Calls method on this specific object (uses car1’s fields).

Key Points:

  • Multiple objects share the class blueprint but have independent data.
  • Fields without static are instance fields (per object).

3. Constructors (Special Methods to Initialize Objects)

Constructors are special methods called automatically on new.

  • Name must match class name.
  • No return type (not even void).
  • If none defined → Java provides default constructor (public ClassName() {}).

Types:

Type Purpose Syntax Example
Default No parameters, sets defaults public Car() {}
Parameterized Takes arguments to initialize fields public Car(String b, String c) { brand = b; color = c; }
Copy (later) Copies another object public Car(Car other) { … }

Complete Example 2: Constructors in Action Update Car.java:

Java

Main.java:

Java

Output:

text

Note: Constructor overloading — multiple constructors with different parameters (like method overloading).

4. The this Keyword (Refers to Current Object)

this points to the current object instance — resolves ambiguity between field and parameter names.

Example in Constructor (from above):

Java

Other Uses:

  • Call another constructor: this(args); (must be first line).
  • Pass current object: someMethod(this);.

Complete Example 3: this in Methods Add to Car.java:

Java

5. Methods: Overloading and Overriding

A. Method Overloading (Compile-Time Polymorphism)

  • Same name, different parameters (number/type/order).
  • Within same class.

Example in Car.java:

Java

Usage in Main:

Java

B. Method Overriding (Runtime Polymorphism)

  • Same name/signature in child class (requires inheritance — preview here, full in Chapter 11).
  • Uses @Override annotation.

Preview Example (add later chapters): Parent: public void start() { System.out.println(“Engine starts”); } Child overrides: @Override public void start() { System.out.println(“Electric engine starts”); }

6. super Keyword (Refers to Parent — Inheritance Preview)

super accesses parent class members. Used in:

  • Constructors: super(); or super(args); (first line).
  • Methods: super.method(); (call parent’s version).

Simple Preview (full inheritance next chapter):

Java

Quick Recap Table (Cheat Sheet)

Concept Key Syntax / Rule Example
Class public class Name { fields; methods; } class Car { String brand; }
Object Type obj = new Type(args); Car c = new Car(“Toyota”);
Default Constructor Auto-provided if none defined new Car();
Parameterized Matches class name, takes params new Car(“Red”, 100);
this Current object: this.field = param; Resolves name conflicts
Method Overloading Same name, different params accelerate(int) vs accelerate(double)
super Parent: super(); super.method(); In child constructors/methods

Common Mistakes & Fixes

Mistake Problem Fix
Accessing private fields directly Compilation error (encapsulation later) Use public getters/setters
Forgetting new NullPointerException later Always Type obj = new Type();
Constructor with return type Compilation error No return type: public Car() {}
Parameter name shadows field Sets param to itself (wrong) Use this.field = param;
Overloading same params different return Not overload (ignores return type) Change param count/type/order
Multiple constructors — no chaining Code duplication Use this(args); to call another ctor

Complete Advanced Example: Library Book System

Integrates all concepts.

Book.java:

Java

Main.java:

Java

Output:

text

Homework (Practice to Master)

  1. Basic: Create Student class with fields (name, rollNo, marks). Add default/parameterized constructors. Create 2 objects, call display method.
  2. Medium: Add overloaded methods to Student: calculateGrade(int marks) and calculateGrade(int[] marksArray). Test both.
  3. Advanced: Create Rectangle class with constructors (default, width+height, copy from another). Use this in copy constructor. Overload area() (no params vs with scaling factor).
  4. Challenge: Fix this buggy code — identify errors:
    Java
  5. Extension: Preview inheritance — make EBook extend Book, use super(title, author, 0).

Mastered OOP basics! This foundation enables Chapters 11+ (inheritance, etc.).

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *