0% found this document useful (0 votes)
7 views56 pages

OOPS Module 3

The document discusses the concept of inheritance in object-oriented programming, explaining its necessity due to code duplication and maintenance challenges. It covers various types of inheritance supported by Java, such as single, multilevel, and hierarchical inheritance, while also addressing the ambiguity issues related to multiple inheritance and how interfaces provide a solution. Additionally, it introduces the fundamental relationships between classes: IS-A, HAS-A, and USES-A, which form the basis for understanding associations, aggregations, and compositions.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views56 pages

OOPS Module 3

The document discusses the concept of inheritance in object-oriented programming, explaining its necessity due to code duplication and maintenance challenges. It covers various types of inheritance supported by Java, such as single, multilevel, and hierarchical inheritance, while also addressing the ambiguity issues related to multiple inheritance and how interfaces provide a solution. Additionally, it introduces the fundamental relationships between classes: IS-A, HAS-A, and USES-A, which form the basis for understanding associations, aggregations, and compositions.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Asst. Prof.

Yash Parashar

Module 3 – Topic 1
Relationship Between Classes: Inheritance

1. Why Inheritance Was Introduced (Problem First)


Before inheritance, programmers faced a major duplication problem.

Situation Without Inheritance:

class Student {
int rollNo;
String name;

void display() {
[Link](rollNo + " " + name);
}
}

class Teacher {
int empId;
String name;

void display() {
[Link](empId + " " + name);
}
}

Problems:

Code duplication (name, display())


Difficult maintenance
Any change → multiple classes
No logical relationship

If tomorrow:

• We want to add address


• We must update every class manually

This clearly violates reusability principle.

2. Real-World Problem Analogy


In a college:

Page | 1
Asst. Prof. Yash Parashar

• Student → name, address


• Teacher → name, address
• Staff → name, address

Would you:

• Write same details again and again?

OR

• Put common properties in one place? ✔

That one common place is called a parent class.

This need gave rise to Inheritance.

3. What is Inheritance?
Simple Definition:

Inheritance is a mechanism where one class acquires the properties and methods of
another class.

Exam-Ready Definition:

Inheritance is an OOP concept that allows a class to reuse the fields and methods of another
class using the extends keyword.

4. Why Inheritance is Important


Inheritance provides:

✔ Code reusability
✔ Reduced redundancy
✔ Easy maintenance
✔ Logical class hierarchy
✔ Supports polymorphism

5. Basic Terminology
Page | 2
Asst. Prof. Yash Parashar

Term Meaning
Parent Class Super class / Base class
Child Class Sub class / Derived class
extends Keyword to inherit

6. Real-World Analogy of Inheritance


Example: Vehicle System

• Vehicle → speed, fuel


• Car → speed, fuel + AC
• Bike → speed, fuel + helmet

Common features inherited


Specific features added

7. Inheritance Syntax in Java


class Parent {
// members
}

class Child extends Parent {


// additional members
}

8. Simple Example of Inheritance (With Full Comments)


// Parent class
class Person {
String name; // common property
int age;

void showPerson() {
[Link]("Name: " + name);
[Link]("Age: " + age);
}
}

// Child class inheriting Person


class Student extends Person {
int rollNo;

void showStudent() {
[Link]("Roll No: " + rollNo);
}
}

// Main class
class Main {

Page | 3
Asst. Prof. Yash Parashar

public static void main(String[] args) {

// Creating object of child class


Student s = new Student();

// Accessing inherited variables


[Link] = "Amit";
[Link] = 20;

// Accessing child specific variable


[Link] = 101;

// Calling inherited method


[Link]();

// Calling child class method


[Link]();
}
}

Key Observations:

✔ Child object can access parent data


✔ Parent does NOT know about child
✔ No duplicate code

9. Memory Concept (Very Important)


When a child object is created:

Parent class memory created first


Child class memory created next

Parent part + Child part = one object

10. Why Java Uses extends Instead of inherit


• Java designers wanted clear semantics
• extends indicates extension, not copy
• Child class adds features, not duplicates

11. What is NOT Inherited in Java


Constructors
Private members

Page | 4
Asst. Prof. Yash Parashar

But:
✔ Constructors are called (via super)
✔ Private members accessed indirectly via methods

12. Common Student Confusions (Very Important)


Confusion 1:

Parent object can access child members

✔ Reality:

• NOT possible

Confusion 2:

Inheritance copies code

✔ Reality:

• It reuses, not copies

Confusion 3:

Java supports all inheritance types

✔ Reality:

• Multiple inheritance via classes not allowed

(Reason covered in next topic)

13. Exam-Oriented Points


• Inheritance improves reusability
• Implemented using extends
• Child inherits non-private members
• Parent constructor executes first
• Java supports single inheritance via class

Page | 5
Asst. Prof. Yash Parashar

14. One-Line Revision


Inheritance allows a class to reuse and extend the features of another class.

Page | 6
Asst. Prof. Yash Parashar

Module 3 – Topic 2
Types of Inheritance in Java

1. Why “Types of Inheritance” Were Needed (Problem


First)
After understanding basic inheritance, programmers started building large systems.

New Problem:

Inheritance was being used in different structural ways, such as:

• One parent → one child


• One parent → many children
• Chain of classes

Without classification:
Design confusion
Poor architecture
Hard to explain relationships

Hence, inheritance was categorized into types.

2. What are Types of Inheritance?


Types of inheritance describe how classes are related to each other in a hierarchy.

Java supports some types directly and some indirectly.

3. Types of Inheritance in OOP (Theoretical)


There are 5 common types:

Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Multiple Inheritance (via class)
Hybrid Inheritance (via class)

Page | 7
Asst. Prof. Yash Parashar

Java supports 1, 2, 3 directly


4 & 5 only via interfaces (later topic)

4. Single Inheritance
Definition:

A child class inherits from one parent class.

Structure:
Parent

Child

Example (With Line-by-Line Comments):

// Parent class
class Animal {
void eat() {
[Link]("Animal is eating");
}
}

// Child class inheriting Animal


class Dog extends Animal {
void bark() {
[Link]("Dog is barking");
}
}

// Main class
class Main {
public static void main(String[] args) {

// Creating object of child class


Dog d = new Dog();

// Calling inherited method


[Link](); // from Animal

// Calling child specific method


[Link](); // from Dog
}
}

Why Single Inheritance is Safe:

Page | 8
Asst. Prof. Yash Parashar

✔ Simple
✔ No ambiguity
✔ Easy to maintain

5. Multilevel Inheritance
Definition:

A class is derived from another derived class (inheritance chain).

Structure:
Grandparent

Parent

Child

Real-World Analogy:

• LivingBeing
• Human
• Student

Example (With Comments):

// Grandparent class
class LivingBeing {
void breathe() {
[Link]("Breathing");
}
}

// Parent class
class Human extends LivingBeing {
void think() {
[Link]("Thinking");
}
}

// Child class
class Student extends Human {
void study() {
[Link]("Studying");
}
}

class Main {

Page | 9
Asst. Prof. Yash Parashar

public static void main(String[] args) {

// Object of most derived class


Student s = new Student();

// Accessing methods from all levels


[Link](); // LivingBeing
[Link](); // Human
[Link](); // Student
}
}

Key Observation:

✔ One object → access to all ancestors


✔ Clear hierarchy

6. Hierarchical Inheritance
Definition:

Multiple child classes inherit from one parent class.

Structure:
Parent
/ \
Child1 Child2

Real-World Analogy:

• Person
o Student
o Teacher

Example (With Comments):


// Parent class
class Person {
void showIdentity() {
[Link]("I am a person");
}
}

// First child
class Student extends Person {

Page | 10
Asst. Prof. Yash Parashar

void study() {
[Link]("Student is studying");
}
}

// Second child
class Teacher extends Person {
void teach() {
[Link]("Teacher is teaching");
}
}

class Main {
public static void main(String[] args) {

Student s = new Student();


Teacher t = new Teacher();

// Student object
[Link]();
[Link]();

// Teacher object
[Link]();
[Link]();
}
}

Benefits:

✔ Code reuse
✔ Logical grouping
✔ Clean design

7. Why Java Does NOT Support Multiple Inheritance (via


Class)
Multiple Inheritance:

One child class inherits from more than one parent class.

Parent1 Parent2
\ /
Child

Problem: Ambiguity (Diamond Problem)


class A {
void show() { }
}

class B {

Page | 11
Asst. Prof. Yash Parashar

void show() { }
}

// ❌ NOT allowed
class C extends A, B {
}

Question:

Which show() should be inherited?


A or B?

Compiler confusion
Ambiguity problem

Real-World Analogy:

Two teachers give different instructions


Student doesn’t know whom to follow

8. Java’s Design Decision (Very Important)


Java designers chose:
✔ Safety
✔ Clarity
✔ No ambiguity

Hence:
Multiple inheritance via classes
✔ Multiple inheritance via interfaces (next topic)

9. Hybrid Inheritance (Why Not Supported Directly)


Hybrid = combination of inheritance types
Since it includes multiple inheritance → not allowed via class

10. Summary Table (Exam Gold)


Type Supported via Class

Page | 12
Asst. Prof. Yash Parashar

Single ✔
Multilevel ✔
Hierarchical ✔
Multiple
Hybrid

11. Common Student Confusions


Confusion 1:

Java does not support inheritance

✔ Reality:

• Java supports inheritance, not multiple via class

Confusion 2:

Multilevel = multiple inheritance

✔ Reality:

• Multilevel = chain
• Multiple = many parents

Page | 13
Asst. Prof. Yash Parashar

Confusion 3:

Ambiguity is runtime problem

✔ Reality:

• Compile-time problem

12. Exam-Oriented Points


• Java supports 3 inheritance types via class
• Multiple inheritance causes ambiguity
• Diamond problem avoided in Java
• Interfaces solve this issue

13. One-Line Revision


Java supports single, multilevel, and hierarchical inheritance, but avoids multiple inheritance
via classes to prevent ambiguity.

Page | 14
Asst. Prof. Yash Parashar

Module 3 – Topic 3
Ambiguity in Multiple Inheritance & Concept of
Interfaces

1. Why This Topic Was Needed (Problem First)


You already saw that:

✔ Inheritance is useful
Multiple inheritance via classes is not allowed in Java

Now the natural question students ask is:

“If multiple inheritance is so useful, why did Java remove it completely?”

Java did not remove the concept, it fixed the problem.

2. What Exactly Is the Ambiguity Problem?


Multiple Inheritance via Classes (NOT allowed)

class A {
void show() {
[Link]("From A");
}
}

class B {
void show() {
[Link]("From B");
}
}

// ❌ This is NOT allowed in Java


class C extends A, B {
}

The Ambiguity Question:

If this were allowed:

C obj = new C();


[Link]();

Page | 15
Asst. Prof. Yash Parashar

Which show() should be called?

• A’s show()?
• B’s show()?

Compiler confusion
This is called the Diamond Problem

3. Real-World Analogy of Ambiguity


A student has:

• Two teachers
• Both give different instructions

Teacher A: “Use pen”


Teacher B: “Use pencil”

Student asks:

“Which one should I follow?”

This confusion = ambiguity

4. Java’s Design Decision (Very Important)


Java designers decided:

✔ Avoid ambiguity
✔ Keep language simple
✔ Ensure predictable behavior

So they said:

No multiple inheritance via classes


✔ Multiple inheritance via interfaces

5. What Is an Interface? (Solution Introduced)

Page | 16
Asst. Prof. Yash Parashar

Simple Definition:

An interface is a collection of abstract methods that defines what a class must do, not how.

Exam-Ready Definition:

An interface is a blueprint of a class that contains abstract methods and is used to achieve
multiple inheritance in Java.

6. Why Interface Solves the Ambiguity Problem


Key idea:

• Interfaces do not contain method implementations


• Only method declarations

No implementation → no conflict

7. Syntax of Interface
interface InterfaceName {
// abstract methods
}

8. Example: Interface Basics (With Full Comments)


// Interface declaration
interface Vehicle {

// abstract method (no body)


void start();
}
// Class implementing interface
class Car implements Vehicle {

// Providing implementation of interface method


public void start() {
[Link]("Car starts with key");
}
}
class Main {
public static void main(String[] args) {

// Creating object of implementing class


Car c = new Car();

// Calling interface method

Page | 17
Asst. Prof. Yash Parashar

[Link]();
}
}

Key Points:

✔ Interface has no implementation


✔ Class provides implementation
✔ No ambiguity

9. Multiple Inheritance Using Interface (MAIN


PURPOSE)
Example (Very Important):

// First interface
interface A {
void show();
}

// Second interface
interface B {
void show();
}

// Class implementing both interfaces


class C implements A, B {

// Single implementation resolves ambiguity


public void show() {
[Link]("Show method implemented once");
}
}

Why No Ambiguity Now?

• Interfaces A & B only declare


• Class C defines
• Compiler knows exactly which method to call

✔ Problem solved

10. Difference: extends vs implements


Keyword Used For
extends Class → Class
implements Class → Interface

Page | 18
Asst. Prof. Yash Parashar

extends Interface → Interface

11. Key Rules of Interfaces (Exam-Important)


✔ Interface methods are public & abstract by default
✔ Variables are public static final
✔ Interface object cannot be created
✔ Class must implement all methods

12. Why Interface Is Better Than Abstract Class (In This


Case)
Abstract Class Interface
Partial implementation No implementation (traditionally)
Single inheritance Multiple inheritance
Has constructors No constructors

13. Common Student Confusions (Very Important)


Confusion 1:

Interface is same as abstract class

✔ Reality:

• Interface is stricter
• Designed for multiple inheritance

Confusion 2:

Interface can have object

✔ Reality:

• Cannot instantiate interface

Confusion 3:

Page | 19
Asst. Prof. Yash Parashar

Interface solves runtime ambiguity

✔ Reality:

• Solves compile-time ambiguity

14. Exam-Oriented Points


• Multiple inheritance via class causes ambiguity
• Java avoids ambiguity by using interfaces
• Interface provides method declaration only
• Class implements multiple interfaces safely

15. One-Line Revision


Java avoids ambiguity in multiple inheritance by using interfaces instead of classes.

Page | 20
Asst. Prof. Yash Parashar

Module 3 – Topic 4
Relationship Modeling: IS-A, HAS-A, USES-A
Association, Aggregation & Composition

1. First: The Real Foundation (Before Definitions)


There are only three fundamental ways classes relate:

Logical Relation OOP Representation Keyword / Structure


IS-A Inheritance extends
HAS-A Object as class member Object inside class
USES-A Method-level interaction Object inside method

Everything else (association, aggregation, composition) comes from these three.

2. IS-A Relationship → Inheritance (extends)


Meaning:

Child is a type of parent.

Real-world:

• Dog IS-A Animal


• Student IS-A Person

Java Structure:
class Animal {
}

class Dog extends Animal {


}

✔ Uses extends
✔ Hierarchical relationship
✔ Supports polymorphism

Page | 21
Asst. Prof. Yash Parashar

3. HAS-A Relationship → Object Inside Class


If one class contains another class object as its member:

// Engine class
class Engine {

String engineType;

// Constructor
Engine(String engineType) {
[Link] = engineType;
}

void startEngine() {
[Link]("Engine of type " + engineType + " is starting...");
}
}

// Car class (HAS-A relationship)


class Car {

Engine engine; // Car HAS-A Engine (reference variable)

String carName;

// Constructor
Car(String carName, Engine engine) {
[Link] = carName;
[Link] = engine; // object passed from outside
}

void startCar() {
[Link](carName + " is starting...");
[Link](); // using Engine object
}
}

// Main class
public class HasARelationshipDemo {

public static void main(String[] args) {

// Engine object created OUTSIDE


Engine e1 = new Engine("Petrol");

// Car object created and Engine passed


Car c1 = new Car("Honda City", e1);

[Link]();
}
}

Output
Honda City is starting...
Engine of type Petrol is starting...

This means:

Page | 22
Asst. Prof. Yash Parashar

Car HAS-A Engine

Important:

• No extends
• It is composition of objects

4. USES-A Relationship → Object Inside Method


If object is used only temporarily inside method:

// Document class
class Document {

String content;

// Constructor
Document(String content) {
[Link] = content;
}

void showContent() {
[Link]("Document Content: " + content);
}
}

// Printer class (USES-A relationship)


class Printer {

// Object is used only inside method


void print(Document d) { // USES-A
[Link]("Printing document...");
[Link](); // using Document object
}
}

// Main class
public class UsesARelationshipDemo {

public static void main(String[] args) {

// Document object created outside


Document doc1 = new Document("OOP Concepts in Java");

// Printer object
Printer printer = new Printer();

// Printer uses Document temporarily


[Link](doc1);
}
}

Output

Page | 23
Asst. Prof. Yash Parashar

Printing document...
Document Content: OOP Concepts in Java

Printer USES Document


But Printer does NOT own Document.

✔ No ownership
✔ Temporary interaction
✔ This is pure Association

5. Now Proper Hierarchy of Specialization Relationships


Very Important:

Association is the base relationship.

Under Association, we classify:

Association
├── Aggregation (weak HAS-A)
└── Composition (strong HAS-A)

So:

• Association = general relationship


• Aggregation = special type of association (weak part-of)
• Composition = special type of association (strong part-of)

6. Association (General Relationship)


Definition:

Association represents a connection between two independent objects.

It can be:

• USES-A
• HAS-A (without ownership clarity)

Example (Pure Association / USES-A)

// Patient class
class Patient {

String name;

Page | 24
Asst. Prof. Yash Parashar

// Constructor
Patient(String name) {
[Link] = name;
}

void getDetails() {
[Link]("Patient Name: " + name);
}
}

// Doctor class (Association - USES-A)


class Doctor {

String doctorName;

// Constructor
Doctor(String doctorName) {
[Link] = doctorName;
}

// USES-A relationship
void treat(Patient p) {
[Link]("Dr. " + doctorName + " is treating the patient...");
[Link](); // Doctor is using Patient object temporarily
}
}

// Main class
public class AssociationDemo {

public static void main(String[] args) {

// Objects created independently


Patient p1 = new Patient("Rahul");
Doctor d1 = new Doctor("Sharma");

// Doctor uses Patient object


[Link](p1);
}
}

Output
Dr. Sharma is treating the patient...
Patient Name: Rahul

Explanation (Clear and Direct)


What type of relationship is this?

This is a Pure Association, specifically a USES-A relationship.

Page | 25
Asst. Prof. Yash Parashar

Why is it Association?

Look carefully at this method:

void treat(Patient p)

• The Doctor class does not have a Patient object as a data member.
• The Patient object is passed as a method parameter.
• The Doctor only uses the Patient temporarily during method execution.

There is:

• No ownership
• No containment
• No part-of relationship

Only interaction.

Independence of Objects

Both objects are created independently in main():

Patient p1 = new Patient("Rahul");


Doctor d1 = new Doctor("Sharma");

• A Patient can exist without a Doctor.


• A Doctor can exist without a Patient.

They are completely independent entities.

Key Concept
Association represents a connection between two independent classes where one class simply
uses the other.

Important Rule
If:

• One class does not store the other as a member variable


• The object is passed only as a method parameter

Page | 26
Asst. Prof. Yash Parashar

Then it is a USES-A (Association) relationship.

7. Aggregation (Weak HAS-A, Weak Part-Of)


Now we refine association.

Definition:

Aggregation is a HAS-A relationship where the child object is part-of the parent, but can
exist independently.

Key Points:

• Weak ownership
• Independent lifecycle
• “Part-of” exists logically
• Object passed from outside

Real-world:

• College HAS-A Teacher


• Team HAS-A Player

Teacher exists without college.

Structural Rule:

✔ Object passed from outside


✔ Not created inside class

Example (Aggregation)

// Teacher class (Independent class)


class Teacher {

String name;

// Constructor
Teacher(String name) {
[Link] = name;
}

void display() {

Page | 27
Asst. Prof. Yash Parashar

[Link]("Teacher Name: " + name);


}
}

// College class (Aggregation: College HAS-A Teacher)


class College {

Teacher teacher; // HAS-A relationship (reference variable)

// Constructor - object passed from outside


College(Teacher teacher) {
[Link] = teacher;
}

void show() {
[Link]("College has teacher: " + [Link]);
}
}

// Main class
public class AggregationDemo {

public static void main(String[] args) {

// Teacher object created independently


Teacher t = new Teacher("Dr. Sharma");

// College object receives Teacher object


College c = new College(t);

[Link]();

// Teacher still exists independently


[Link]();
}
}

Output
College has teacher: Dr. Sharma
Teacher Name: Dr. Sharma

Explanation (Precise and Technical)


Why This is Aggregation?

Look at this line:

Teacher teacher;

• College contains a reference to a Teacher.


• That means College HAS-A Teacher.
• But the Teacher object is created outside the College class:

Page | 28
Asst. Prof. Yash Parashar

Teacher t = new Teacher("Dr. Sharma");

Then passed into College:

College c = new College(t);

So:

• The object is not created inside College.


• College is not the owner.
• It only stores a reference.

Key Characteristics Present

✔ Weak ownership
✔ Teacher is logically part of College
✔ Teacher can exist without College
✔ Lifecycle is independent
✔ Object passed from outside

Why It Is Not Composition

If this line were written inside College:

Teacher teacher = new Teacher("Dr. Sharma");

Then College would be creating and controlling the object.


That would be Composition (strong HAS-A).

But here, object creation happens externally.


Therefore → Aggregation.

Structural Rule (Important for Exams)


Aggregation exists when:

• One class has another class as a data member.


• The object is created outside.
• The object is passed via constructor or setter.
• Both objects can exist independently.

Page | 29
Asst. Prof. Yash Parashar

8. Composition (Strong HAS-A, Strong Part-Of)


Definition:

Composition is a strong HAS-A relationship where the child object’s lifecycle depends on the
parent.

Key Points:

• Strong ownership
• Child created inside parent
• Destroy parent → child destroyed
• Strong “part-of”

Real-world:

• House HAS-A Room


• Human HAS-A Heart

Room cannot exist without House.

Structural Rule:
✔ Object created inside class
✔ Parent controls lifecycle

Example (Composition)
// Engine class
class Engine {

void start() {
[Link]("Engine started");
}
}

// Car class (Composition: Strong HAS-A)


class Car {

private Engine engine; // Strong ownership

// Constructor - Engine created inside Car


Car() {

Page | 30
Asst. Prof. Yash Parashar

engine = new Engine(); // Object created internally


}

void drive() {
[Link]();
[Link]("Car is moving");
}
}

// Main class
public class CompositionDemo {

public static void main(String[] args) {

Car car = new Car(); // Only Car object created


[Link]();
}
}

Output
Engine started
Car is moving

Technical Explanation
Why This is Composition

Look at this line inside Car:

engine = new Engine();

• The Engine object is created inside the Car class.


• It is not passed from outside.
• The Car class controls its creation.
• No external class has access to create or inject the Engine.

This means:

✔ Strong ownership
✔ Lifecycle controlled by Car
✔ Engine depends on Car

Lifecycle Control

In main():

Page | 31
Asst. Prof. Yash Parashar

Car car = new Car();

Only the Car object is created explicitly.


The Engine is automatically created when the Car constructor runs.

If the Car object becomes eligible for garbage collection,


the Engine object also becomes unreachable.

That is lifecycle dependency.

Why This Is Not Aggregation

In Aggregation:

Engine e = new Engine();


Car c = new Car(e);

Object created outside → weak ownership.

Here:

engine = new Engine();

Object created inside → strong ownership.

That is the structural difference.

Structural Rule (Exam Important)


Composition exists when:

• One class contains another as a data member.


• The object is created inside the containing class.
• The parent controls the lifecycle.
• The child object cannot meaningfully exist without the parent.

Conceptual Summary

Page | 32
Asst. Prof. Yash Parashar

Composition is a strong form of aggregation where the contained object’s lifecycle is bound
to the container.

9. “Part-Of” Clarification (Very Important)


Relationship Part-Of Exists? Lifecycle Dependency
Association Not necessarily
Aggregation ✔ Weak part-of
Composition ✔ Strong part-of ✔

This distinction is critical and must be taught clearly.

10. Full Concept Mapping (This Was Missing Earlier)


Concept Representation in Code
IS-A extends
HAS-A Object inside class
USES-A Object inside method
Aggregation Object passed from outside
Composition Object created inside class

Now everything is properly aligned.

11. Why These Distinctions Matter


If students confuse:

• IS-A vs HAS-A
• Aggregation vs Composition

They will:

• Build wrong class hierarchies


• Create tight coupling
• Fail in design interviews

This is not theory — this is architecture.

12. Final Structured Summary


Page | 33
Asst. Prof. Yash Parashar

Relationships in OOP:

1. IS-A → Inheritance → extends


2. HAS-A → Object inside class
├── Aggregation → weak part-of, independent
└── Composition → strong part-of, dependent
3. USES-A → Object inside method

Page | 34
Asst. Prof. Yash Parashar

Module 3 – Topic 5
Polymorphism: Static & Dynamic Binding, Method
Overloading & Method Overriding

1. Why Polymorphism Was Introduced (Problem First)


Till now, we had:

• Classes
• Inheritance
• Methods

But programmers faced a design limitation:

Same operation
Different objects
Different behavior

Problem Without Polymorphism

class Circle {
void areaCircle() { }
}

class Rectangle {
void areaRectangle() { }
}

Problems:
Different method names for same operation
Code becomes confusing
No standard interface
Poor extensibility

Real systems need same action, different behavior.

2. Real-World Analogy (Foundation)


Example: Remote Button

• Same Power button


• TV → turns ON TV

Page | 35
Asst. Prof. Yash Parashar

• AC → turns ON AC
• Speaker → turns ON speaker

Button is same
Action differs

This concept is called Polymorphism.

3. What is Polymorphism?
Simple Definition:

Polymorphism means one name, many forms.

Exam-Ready Definition:

Polymorphism is an OOP concept where a single method name behaves differently


depending on the object or context.

4. Types of Polymorphism in Java


Java supports two types:

Compile-Time Polymorphism
→ Method Overloading
→ Static Binding

Run-Time Polymorphism
→ Method Overriding
→ Dynamic Binding

PART A — Compile-Time Polymorphism


Method Overloading + Static Binding

5. Why Method Overloading Was Needed


Page | 36
Asst. Prof. Yash Parashar

Problem:

Same operation, different inputs.

Example:

• Add 2 numbers
• Add 3 numbers
• Add decimals

Without overloading:
add2(), add3(), addDouble()
Ugly API
Poor readability

Same name, different parameters was required.

6. What is Method Overloading?


Method overloading means defining multiple methods with the same name but different
parameter lists in the same class.

7. Complete Example: Method Overloading (With Full


Comments)
class Calculator {

// Method to add two integers


int add(int a, int b) {
return a + b;
}

// Method to add three integers


int add(int a, int b, int c) {
return a + b + c;
}

// Method to add two decimal numbers


double add(double a, double b) {
return a + b;
}
}

class Main {
public static void main(String[] args) {

// Creating object of Calculator


Calculator calc = new Calculator();

// Compile-time decision: which method to call


[Link]([Link](10, 20)); // calls add(int, int)

Page | 37
Asst. Prof. Yash Parashar

[Link]([Link](1, 2, 3)); // calls add(int, int, int)


[Link]([Link](2.5, 3.5)); // calls add(double, double)
}
}

Key Observation:

✔ Method call decided at compile time


✔ Based on parameter list
✔ No inheritance required

8. Static Binding (Why It Happens Here)


Definition:

Static binding means method call is resolved at compile time.

Why?

• Object type known


• Method signature known
• No ambiguity at runtime

9. Common Confusions in Overloading


Changing return type only → NOT overloading
Changing access modifier → NOT overloading
Overloading works across inheritance → (that is overriding)

PART B — Run-Time Polymorphism


Method Overriding + Dynamic Binding

10. Why Method Overriding Was Needed


Inheritance introduced another challenge.

Problem Example:
Page | 38
Asst. Prof. Yash Parashar

class Vehicle {
void start() {
[Link]("Vehicle starts");
}
}

Child classes:

• Car
• Bike

Should they start same way?

Child must modify parent behavior.

11. What is Method Overriding?


Method overriding occurs when a child class provides its own implementation of a parent
class method.

12. Complete Example: Method Overriding (With Full


Comments)
// Parent class
class Vehicle {

// Method to be overridden
void start() {
[Link]("Vehicle starts");
}
}

// Child class
class Car extends Vehicle {

// Overriding parent method


void start() {
[Link]("Car starts with key");
}
}

// Another child class


class Bike extends Vehicle {

// Overriding parent method


void start() {
[Link]("Bike starts with kick");
}
}

class Main {
public static void main(String[] args) {

Page | 39
Asst. Prof. Yash Parashar

// Parent reference, child object


Vehicle v1 = new Car();
Vehicle v2 = new Bike();

// Runtime decides which method to call


[Link](); // Car's start()
[Link](); // Bike's start()
}
}

13. Dynamic Binding (MOST IMPORTANT CONCEPT)


Definition:

Dynamic binding means method call is resolved at runtime, based on the actual object.

Why Runtime?

• Reference type = Vehicle


• Object type = Car / Bike
• JVM checks actual object, not reference

14. Key Rules of Method Overriding


✔ Method name must be same
✔ Parameters must be same
✔ IS-A relationship required
✔ Access level cannot be reduced
✔ Static methods cannot be overridden

15. Static vs Dynamic Binding (Exam Gold)


Feature Static Binding Dynamic Binding
Decision time Compile time Runtime
Used with Overloading Overriding
Reference Direct Object based
Performance Faster Slightly slower

16. Very Common Student Confusions (Important)

Page | 40
Asst. Prof. Yash Parashar

Confusion 1:

Overloading depends on return type

✔ Reality:

• Depends only on parameters

Confusion 2:

Overriding works without inheritance

✔ Reality:

• Inheritance is mandatory

Confusion 3:

Parent reference cannot call child method

✔ Reality:

• Can call overridden methods only

17. Why Polymorphism Is Extremely Important


✔ Flexibility
✔ Loose coupling
✔ Code scalability
✔ Clean architecture
✔ Core of frameworks (Spring, Hibernate)

18. Exam-Oriented Summary


• Polymorphism = one name, many behaviors
• Overloading → compile-time → static binding
• Overriding → runtime → dynamic binding
• Overriding depends on actual object
• Parent reference, child object enables polymorphism

Page | 41
Asst. Prof. Yash Parashar

19. One-Line Revision


Polymorphism allows the same method name to perform different behaviors using
overloading and overriding.

Page | 42
Asst. Prof. Yash Parashar

Why Do We Create Parent Reference


Variables in Method Overriding (Runtime
Polymorphism)?

1. Core Statement
In Java, we use a parent class reference variable to refer to child class objects in order to
achieve runtime polymorphism (dynamic method dispatch).

Vehicle v = new Car();

Here:

• Vehicle → reference type (compile-time type)


• Car → object type (runtime type)

2. What Problem Does It Solve?


Without parent reference, you would need:

Car c = new Car();


Bike b = new Bike();
Truck t = new Truck();

And separate logic:

[Link]();
[Link]();
[Link]();

This creates:

• Code duplication
• Tight coupling
• Poor scalability

3. Generic Programming Using Parent Reference

Page | 43
Asst. Prof. Yash Parashar

Using parent reference:

void testDrive(Vehicle v){


[Link]();
}

Now you can pass:

testDrive(new Car());
testDrive(new Bike());
testDrive(new Truck());

✔ Same method
✔ Same call
✔ Different behavior

This is runtime polymorphism.

4. What Actually Happens Internally?


Compile-Time:

Compiler checks:

• Does Vehicle class contain start()? ✔ Yes.

Runtime:

JVM checks:

• Which object is v pointing to?


o If Car → call [Link]()
o If Bike → call [Link]()

This mechanism is called:

Dynamic Method Dispatch

5. Why Not Use Child Reference Always?


If we write:

Car c = new Car();

Page | 44
Asst. Prof. Yash Parashar

Then:

• We can only store Car


• Cannot store Bike or Truck
• No generic handling possible

Example:

Car[] cars = new Car[10];

You cannot store Bike in it.

But:

Vehicle[] vehicles = new Vehicle[10];

Now you can store:

vehicles[0] = new Car();


vehicles[1] = new Bike();
vehicles[2] = new Truck();

That is flexibility.

6. Key Advantages of Parent Reference


1. Achieves Runtime Polymorphism

Method call depends on object type.

2. Promotes Loose Coupling

Code depends on abstraction (Vehicle), not implementation (Car).

3. Improves Extensibility

If tomorrow you add:

class Bus extends Vehicle

No changes required in testDrive().

4. Supports Open-Closed Principle

Page | 45
Asst. Prof. Yash Parashar

Open for extension


Closed for modification

7. Important Technical Rule


In Java:

• Method overriding works only with reference type of parent


• Method execution depends on object type of child

Formula:

Reference Type → Compile-time checking


Object Type → Runtime execution

8. What Parent Reference Restricts


Example:

Vehicle v = new Car();


[Link](); // Compile-time error

Even though object is Car, compiler only sees Vehicle methods.

So:

Parent reference provides:

• Abstraction
• Controlled access
• Safety

9. Conceptual Understanding
Parent reference is not about storing address.

It is about:

Writing generic, flexible, scalable, loosely coupled code


where behavior is decided at runtime.

Page | 46
Asst. Prof. Yash Parashar

10. Final Conclusion (Exam-Oriented Answer)


We create a parent class reference variable in method overriding to:

1. Enable runtime polymorphism


2. Allow dynamic method dispatch
3. Achieve generic programming
4. Promote loose coupling
5. Improve extensibility and maintainability

Without parent reference, polymorphism is not possible.

Page | 47
Asst. Prof. Yash Parashar

Module 3 – Topic 6
Keywords in Java: super, abstract, final

1. Why These Keywords Were Needed (Big Picture First)


After introducing:

• Inheritance
• Polymorphism
• Method overriding

Three practical problems appeared:

Child could not clearly access parent data


Some classes were incomplete by design
Sometimes inheritance or overriding needed to be stopped intentionally

These problems led to the introduction of:

• super
• abstract
• final

Each keyword solves a different design problem.

PART A — super Keyword

2. Why super Keyword Was Needed (Problem First)


Problem Scenario

class Person {
String name = "Parent Name";
}

class Student extends Person {


String name = "Child Name";

void show() {
[Link](name);
}
}

Page | 48
Asst. Prof. Yash Parashar

Output:
Child Name

Problem:

• Parent’s name exists


• But child cannot access it directly
• Parent data is shadowed

Java needed a way to explicitly refer to parent class.

3. What is super Keyword?


Simple Definition:

super is a reference variable that refers to the immediate parent class object.

Exam-Ready Definition:

The super keyword is used to access parent class variables, methods, and constructors from a
child class.

4. Uses of super Keyword (3 Important Uses)

Use 1: Access Parent Class Variable


Complete Example (Fully Commented)

class Person {
String name = "Parent Name";
}

class Student extends Person {


String name = "Child Name";

void showNames() {
// Refers to child class variable
[Link]("Child name: " + name);

Page | 49
Asst. Prof. Yash Parashar

// Refers to parent class variable


[Link]("Parent name: " + [Link]);
}
}

class Main {
public static void main(String[] args) {
Student s = new Student();
[Link]();
}
}

Output:
Child name: Child Name
Parent name: Parent Name

✔ [Link] removes ambiguity


✔ Similar to this but for parent

Use 2: Call Parent Class Method


Problem:

Child overrides method, but still needs parent behavior.

Complete Example:

class Vehicle {
void start() {
[Link]("Vehicle starts");
}
}

class Car extends Vehicle {

void start() {
// Calling parent version
[Link]();

// Child specific behavior


[Link]("Car starts with key");
}
}

class Main {
public static void main(String[] args) {
Car c = new Car();
[Link]();
}
}

Page | 50
Asst. Prof. Yash Parashar

Output:
Vehicle starts
Car starts with key

✔ Reuse parent logic


✔ Extend behavior safely

Use 3: Call Parent Class Constructor


Problem:

Parent needs initialization before child.

Complete Example:

class Person {
Person() {
[Link]("Person constructor called");
}
}

class Student extends Person {

Student() {
// Calls parent constructor
super();

[Link]("Student constructor called");


}
}

class Main {
public static void main(String[] args) {
Student s = new Student();
}
}

Output:
Person constructor called
Student constructor called

✔ Parent constructor executes first


✔ Ensures proper object creation

5. Common Confusions About super


Page | 51
Asst. Prof. Yash Parashar

super creates a parent object


✔ No, object already exists

super can be used in static methods


✔ Not allowed

superand this are same


✔ this → current object
✔ super → parent object

PART B — abstract Keyword

6. Why abstract Keyword Was Needed (Problem First)


Problem Scenario

Some classes are conceptual, not complete.

Example:

• Shape
• Vehicle
• Bank

You cannot:

• Create Shape directly


• Define full behavior

Java needed incomplete classes that enforce implementation.

7. What is abstract Keyword?


Definition:

abstract keyword is used to create incomplete classes and methods that must be
implemented by subclasses.

Page | 52
Asst. Prof. Yash Parashar

8. Abstract Class Example (Fully Commented)


// Abstract class
abstract class Shape {

// Abstract method (no body)


abstract void area();
}

class Circle extends Shape {

void area() {
[Link]("Area of Circle = πr²");
}
}

class Rectangle extends Shape {

void area() {
[Link]("Area of Rectangle = length × breadth");
}
}

class Main {
public static void main(String[] args) {

// Shape reference, Circle object


Shape s1 = new Circle();
[Link]();

// Shape reference, Rectangle object


Shape s2 = new Rectangle();
[Link]();
}
}

✔ Abstract class cannot be instantiated


✔ Forces child classes to implement methods
✔ Supports polymorphism

9. Rules of Abstract Keyword


✔ Abstract class may have concrete methods
✔ Abstract method has no body
✔ Child must implement all abstract methods
✔ Abstract constructor exists
✔ Abstract class cannot be final

10. Common Confusions About abstract

Page | 53
Asst. Prof. Yash Parashar

Abstract class has no methods


✔ It can have both

Abstract method can be private


✔ Not allowed

Object of abstract class can be created


✔ Impossible

PART C — final Keyword

11. Why final Keyword Was Needed (Problem First)


Inheritance is powerful, but sometimes dangerous.

Problems:

• Security classes overridden


• Logic changed accidentally
• Critical behavior modified

Java needed a way to STOP changes.

12. What is final Keyword?


final keyword is used to restrict modification.

It can be used with:


Variables
Methods
Classes

13. final Variable Example


class Test {
final int MAX = 100;

void change() {
// MAX = 200; ❌ Not allowed

Page | 54
Asst. Prof. Yash Parashar

}
}

✔ Value cannot change


✔ Acts like constant

14. final Method Example


class Parent {
final void show() {
[Link]("This method cannot be overridden");
}
}

class Child extends Parent {

// void show() { } ❌ Compile-time error


}

✔ Prevents overriding
✔ Ensures fixed behavior

15. final Class Example


final class SecuritySystem {
void access() {
[Link]("Secure Access");
}
}

// class Hacker extends SecuritySystem ❌ Not allowed

✔ Prevents inheritance
✔ Used for security-critical classes

16. abstract vs final (Exam Gold)


abstract final
Incomplete Complete
Must be inherited Cannot be inherited
Methods must be overridden Methods cannot be overridden

Page | 55
Asst. Prof. Yash Parashar

17. Very Common Student Confusions


final means constant only
✔ Applies to class & method too

Abstract and final can be together


✔ Never possible

super() is optional
✔ Compiler inserts it if missing

18. Exam-Oriented Summary


• super accesses parent members
• abstract enforces implementation
• final prevents modification
• abstract supports polymorphism
• final improves security

19. One-Line Revision


• super → access parent
• abstract → incomplete design
• final → stop changes

Module-3 COMPLETED SUCCESSFULLY


Covered:

✔ Inheritance & Types


✔ Interfaces & Ambiguity
✔ HAS-A Relationships
✔ Polymorphism
✔ super, abstract, final

Page | 56

You might also like