OOPS Module 3
OOPS Module 3
Yash Parashar
Module 3 – Topic 1
Relationship Between Classes: Inheritance
class Student {
int rollNo;
String name;
void display() {
[Link](rollNo + " " + name);
}
}
class Teacher {
int empId;
String name;
void display() {
[Link](empId + " " + name);
}
}
Problems:
If tomorrow:
Page | 1
Asst. Prof. Yash Parashar
Would you:
OR
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.
✔ 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
void showPerson() {
[Link]("Name: " + name);
[Link]("Age: " + age);
}
}
void showStudent() {
[Link]("Roll No: " + rollNo);
}
}
// Main class
class Main {
Page | 3
Asst. Prof. Yash Parashar
Key Observations:
Page | 4
Asst. Prof. Yash Parashar
But:
✔ Constructors are called (via super)
✔ Private members accessed indirectly via methods
✔ Reality:
• NOT possible
Confusion 2:
✔ Reality:
Confusion 3:
✔ Reality:
Page | 5
Asst. Prof. Yash Parashar
Page | 6
Asst. Prof. Yash Parashar
Module 3 – Topic 2
Types of Inheritance in Java
New Problem:
Without classification:
Design confusion
Poor architecture
Hard to explain relationships
Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Multiple Inheritance (via class)
Hybrid Inheritance (via class)
Page | 7
Asst. Prof. Yash Parashar
4. Single Inheritance
Definition:
Structure:
Parent
↓
Child
// Parent class
class Animal {
void eat() {
[Link]("Animal is eating");
}
}
// Main class
class Main {
public static void main(String[] args) {
Page | 8
Asst. Prof. Yash Parashar
✔ Simple
✔ No ambiguity
✔ Easy to maintain
5. Multilevel Inheritance
Definition:
Structure:
Grandparent
↓
Parent
↓
Child
Real-World Analogy:
• LivingBeing
• Human
• Student
// 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
Key Observation:
6. Hierarchical Inheritance
Definition:
Structure:
Parent
/ \
Child1 Child2
Real-World Analogy:
• Person
o Student
o Teacher
// 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 object
[Link]();
[Link]();
// Teacher object
[Link]();
[Link]();
}
}
Benefits:
✔ Code reuse
✔ Logical grouping
✔ Clean design
One child class inherits from more than one parent class.
Parent1 Parent2
\ /
Child
class B {
Page | 11
Asst. Prof. Yash Parashar
void show() { }
}
// ❌ NOT allowed
class C extends A, B {
}
Question:
Compiler confusion
Ambiguity problem
Real-World Analogy:
Hence:
Multiple inheritance via classes
✔ Multiple inheritance via interfaces (next topic)
Page | 12
Asst. Prof. Yash Parashar
Single ✔
Multilevel ✔
Hierarchical ✔
Multiple
Hybrid
✔ Reality:
Confusion 2:
✔ Reality:
• Multilevel = chain
• Multiple = many parents
Page | 13
Asst. Prof. Yash Parashar
Confusion 3:
✔ Reality:
• Compile-time problem
Page | 14
Asst. Prof. Yash Parashar
Module 3 – Topic 3
Ambiguity in Multiple Inheritance & Concept of
Interfaces
✔ Inheritance is useful
Multiple inheritance via classes is not allowed in Java
class A {
void show() {
[Link]("From A");
}
}
class B {
void show() {
[Link]("From B");
}
}
Page | 15
Asst. Prof. Yash Parashar
• A’s show()?
• B’s show()?
Compiler confusion
This is called the Diamond Problem
• Two teachers
• Both give different instructions
Student asks:
✔ Avoid ambiguity
✔ Keep language simple
✔ Ensure predictable behavior
So they said:
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.
No implementation → no conflict
7. Syntax of Interface
interface InterfaceName {
// abstract methods
}
Page | 17
Asst. Prof. Yash Parashar
[Link]();
}
}
Key Points:
// First interface
interface A {
void show();
}
// Second interface
interface B {
void show();
}
✔ Problem solved
Page | 18
Asst. Prof. Yash Parashar
✔ Reality:
• Interface is stricter
• Designed for multiple inheritance
Confusion 2:
✔ Reality:
Confusion 3:
Page | 19
Asst. Prof. Yash Parashar
✔ Reality:
Page | 20
Asst. Prof. Yash Parashar
Module 3 – Topic 4
Relationship Modeling: IS-A, HAS-A, USES-A
Association, Aggregation & Composition
Real-world:
Java Structure:
class Animal {
}
✔ Uses extends
✔ Hierarchical relationship
✔ Supports polymorphism
Page | 21
Asst. Prof. Yash Parashar
// Engine class
class Engine {
String engineType;
// Constructor
Engine(String engineType) {
[Link] = engineType;
}
void startEngine() {
[Link]("Engine of type " + engineType + " is starting...");
}
}
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 {
[Link]();
}
}
Output
Honda City is starting...
Engine of type Petrol is starting...
This means:
Page | 22
Asst. Prof. Yash Parashar
Important:
• No extends
• It is composition of objects
// Document class
class Document {
String content;
// Constructor
Document(String content) {
[Link] = content;
}
void showContent() {
[Link]("Document Content: " + content);
}
}
// Main class
public class UsesARelationshipDemo {
// Printer object
Printer printer = new Printer();
Output
Page | 23
Asst. Prof. Yash Parashar
Printing document...
Document Content: OOP Concepts in Java
✔ No ownership
✔ Temporary interaction
✔ This is pure Association
Association
├── Aggregation (weak HAS-A)
└── Composition (strong HAS-A)
So:
It can be:
• USES-A
• HAS-A (without ownership clarity)
// Patient class
class Patient {
String name;
Page | 24
Asst. Prof. Yash Parashar
// Constructor
Patient(String name) {
[Link] = name;
}
void getDetails() {
[Link]("Patient Name: " + name);
}
}
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 {
Output
Dr. Sharma is treating the patient...
Patient Name: Rahul
Page | 25
Asst. Prof. Yash Parashar
Why is it Association?
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
Key Concept
Association represents a connection between two independent classes where one class simply
uses the other.
Important Rule
If:
Page | 26
Asst. Prof. Yash Parashar
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:
Structural Rule:
Example (Aggregation)
String name;
// Constructor
Teacher(String name) {
[Link] = name;
}
void display() {
Page | 27
Asst. Prof. Yash Parashar
void show() {
[Link]("College has teacher: " + [Link]);
}
}
// Main class
public class AggregationDemo {
[Link]();
Output
College has teacher: Dr. Sharma
Teacher Name: Dr. Sharma
Teacher teacher;
Page | 28
Asst. Prof. Yash Parashar
So:
✔ Weak ownership
✔ Teacher is logically part of College
✔ Teacher can exist without College
✔ Lifecycle is independent
✔ Object passed from outside
Page | 29
Asst. Prof. Yash Parashar
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:
Structural Rule:
✔ Object created inside class
✔ Parent controls lifecycle
Example (Composition)
// Engine class
class Engine {
void start() {
[Link]("Engine started");
}
}
Page | 30
Asst. Prof. Yash Parashar
void drive() {
[Link]();
[Link]("Car is moving");
}
}
// Main class
public class CompositionDemo {
Output
Engine started
Car is moving
Technical Explanation
Why This is Composition
This means:
✔ Strong ownership
✔ Lifecycle controlled by Car
✔ Engine depends on Car
Lifecycle Control
In main():
Page | 31
Asst. Prof. Yash Parashar
In Aggregation:
Here:
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.
• IS-A vs HAS-A
• Aggregation vs Composition
They will:
Relationships in OOP:
Page | 34
Asst. Prof. Yash Parashar
Module 3 – Topic 5
Polymorphism: Static & Dynamic Binding, Method
Overloading & Method Overriding
• Classes
• Inheritance
• Methods
Same operation
Different objects
Different behavior
class Circle {
void areaCircle() { }
}
class Rectangle {
void areaRectangle() { }
}
Problems:
Different method names for same operation
Code becomes confusing
No standard interface
Poor extensibility
Page | 35
Asst. Prof. Yash Parashar
• AC → turns ON AC
• Speaker → turns ON speaker
Button is same
Action differs
3. What is Polymorphism?
Simple Definition:
Exam-Ready Definition:
Compile-Time Polymorphism
→ Method Overloading
→ Static Binding
Run-Time Polymorphism
→ Method Overriding
→ Dynamic Binding
Problem:
Example:
• Add 2 numbers
• Add 3 numbers
• Add decimals
Without overloading:
add2(), add3(), addDouble()
Ugly API
Poor readability
class Main {
public static void main(String[] args) {
Page | 37
Asst. Prof. Yash Parashar
Key Observation:
Why?
Problem Example:
Page | 38
Asst. Prof. Yash Parashar
class Vehicle {
void start() {
[Link]("Vehicle starts");
}
}
Child classes:
• Car
• Bike
// Method to be overridden
void start() {
[Link]("Vehicle starts");
}
}
// Child class
class Car extends Vehicle {
class Main {
public static void main(String[] args) {
Page | 39
Asst. Prof. Yash Parashar
Dynamic binding means method call is resolved at runtime, based on the actual object.
Why Runtime?
Page | 40
Asst. Prof. Yash Parashar
Confusion 1:
✔ Reality:
Confusion 2:
✔ Reality:
• Inheritance is mandatory
Confusion 3:
✔ Reality:
Page | 41
Asst. Prof. Yash Parashar
Page | 42
Asst. Prof. Yash Parashar
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).
Here:
[Link]();
[Link]();
[Link]();
This creates:
• Code duplication
• Tight coupling
• Poor scalability
Page | 43
Asst. Prof. Yash Parashar
testDrive(new Car());
testDrive(new Bike());
testDrive(new Truck());
✔ Same method
✔ Same call
✔ Different behavior
Compiler checks:
Runtime:
JVM checks:
Page | 44
Asst. Prof. Yash Parashar
Then:
Example:
But:
That is flexibility.
3. Improves Extensibility
Page | 45
Asst. Prof. Yash Parashar
Formula:
So:
• Abstraction
• Controlled access
• Safety
9. Conceptual Understanding
Parent reference is not about storing address.
It is about:
Page | 46
Asst. Prof. Yash Parashar
Page | 47
Asst. Prof. Yash Parashar
Module 3 – Topic 6
Keywords in Java: super, abstract, final
• Inheritance
• Polymorphism
• Method overriding
• super
• abstract
• final
class Person {
String name = "Parent Name";
}
void show() {
[Link](name);
}
}
Page | 48
Asst. Prof. Yash Parashar
Output:
Child Name
Problem:
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.
class Person {
String name = "Parent Name";
}
void showNames() {
// Refers to child class variable
[Link]("Child name: " + name);
Page | 49
Asst. Prof. Yash Parashar
class Main {
public static void main(String[] args) {
Student s = new Student();
[Link]();
}
}
Output:
Child name: Child Name
Parent name: Parent Name
Complete Example:
class Vehicle {
void start() {
[Link]("Vehicle starts");
}
}
void start() {
// Calling parent version
[Link]();
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
Complete Example:
class Person {
Person() {
[Link]("Person constructor called");
}
}
Student() {
// Calls parent constructor
super();
class Main {
public static void main(String[] args) {
Student s = new Student();
}
}
Output:
Person constructor called
Student constructor called
Example:
• Shape
• Vehicle
• Bank
You cannot:
abstract keyword is used to create incomplete classes and methods that must be
implemented by subclasses.
Page | 52
Asst. Prof. Yash Parashar
void area() {
[Link]("Area of Circle = πr²");
}
}
void area() {
[Link]("Area of Rectangle = length × breadth");
}
}
class Main {
public static void main(String[] args) {
Page | 53
Asst. Prof. Yash Parashar
Problems:
void change() {
// MAX = 200; ❌ Not allowed
Page | 54
Asst. Prof. Yash Parashar
}
}
✔ Prevents overriding
✔ Ensures fixed behavior
✔ Prevents inheritance
✔ Used for security-critical classes
Page | 55
Asst. Prof. Yash Parashar
super() is optional
✔ Compiler inserts it if missing
Page | 56