Docsity

Polymorphism in Java: A Comprehensive Guide - Prof. gour, Study notes of Computer Science

Toggle sidebar
bg1
Topic Name: Polymorphism in Java
Introduction of the Topic
Clear Definition
Polymorphism, derived from Greek words poly (many) and morph (forms), is a
fundamental Object-Oriented Programming (OOP) concept in Java that allows
objects of different classes to be treated as objects of a common superclass. It
enables a single interface to represent different underlying forms (data types).
Technical Definition: Polymorphism is the ability of an object to take on many
forms, specifically allowing:
1. A reference variable of a superclass type to refer to an object of its
subclass
2. A method to behave differently based on the object it is acting upon
Why This Concept is Important in Java
● Core OOP Pillar: One of the four fundamental OOP principles
(Abstraction, Encapsulation, Inheritance, Polymorphism)
● Code Flexibility: Enables writing flexible and extensible code that can
work with objects of multiple types
● Maintainability: Reduces code duplication and makes systems easier to
maintain and extend
● Runtime Decision Making: Allows decisions about which method to
execute to be made at runtime (dynamic method dispatch)
● Foundation for Frameworks: Essential for Java frameworks like Spring,
Hibernate, and Java Collections Framework
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37

Partial preview of the text

Download Polymorphism in Java: A Comprehensive Guide - Prof. gour and more Study notes Computer Science in PDF only on Docsity!

Topic Name: Polymorphism in Java

Introduction of the Topic

Clear Definition

Polymorphism, derived from Greek words poly (many) and morph (forms), is a

fundamental Object-Oriented Programming (OOP) concept in Java that allows

objects of different classes to be treated as objects of a common superclass. It

enables a single interface to represent different underlying forms (data types).

Technical Definition: Polymorphism is the ability of an object to take on many

forms, specifically allowing:

1. A reference variable of a superclass type to refer to an object of its

subclass

2. A method to behave differently based on the object it is acting upon

Why This Concept is Important in Java

● Core OOP Pillar: One of the four fundamental OOP principles

(Abstraction, Encapsulation, Inheritance, Polymorphism)

● Code Flexibility: Enables writing flexible and extensible code that can

work with objects of multiple types

● Maintainability: Reduces code duplication and makes systems easier to

maintain and extend

● Runtime Decision Making: Allows decisions about which method to

execute to be made at runtime (dynamic method dispatch)

● Foundation for Frameworks: Essential for Java frameworks like Spring,

Hibernate, and Java Collections Framework

Where It is Used in Real-World Applications

1. Payment Processing Systems: Single processPayment() method

handling CreditCard, PayPal, UPI payments

2. GUI Frameworks: draw() method behaving differently for Circle,

Rectangle, Triangle objects

3. Database Operations: Common interface for different database

implementations (MySQL, Oracle, PostgreSQL)

4. Logging Frameworks: Different loggers (FileLogger, ConsoleLogger,

DatabaseLogger) with same interface

5. Game Development: render() and update() methods for different game

entities (Player, Enemy, Item)

Detailed Theory Explanation Two Types of Polymorphism in Java

1. Compile-Time Polymorphism (Static Polymorphism)

● Achieved through Method Overloading

● Decision about which method to call is made at compile time

● Characteristics:

○ Multiple methods with same name in same class

○ Different parameter lists (type, number, or sequence)

○ Return type may or may not be different (return type alone

cannot differentiate overloaded methods)

○ Can be within same class or between parent-child classes

2. Runtime Polymorphism (Dynamic Polymorphism)

● Achieved through Method Overriding

● Decision about which method to call is made at runtime

● Characteristics:

3. final - prevents overriding 4. abstract - enforces overriding 5. @Override - annotation for overridden methods Limitations and Constraints

1. Instance Variables: Polymorphism doesn't apply to instance variables

(resolved at compile time based on reference type)

2. Static Methods: Cannot be overridden, only hidden

3. Private Methods: Not polymorphic

4. Constructors: Cannot be overridden (not inherited)

5. Final Methods: Cannot participate in runtime polymorphism

6. Access Restrictions: Overriding method cannot reduce visibility

Syntax & Code Explanation Basic Syntax Structure java // Parent class class Parent { // Method to be overridden public void display () { System. out. println ( "Parent's display" ); } // Overloaded method public void show ( int x ) { System. out. println ( "Parent show with int: " + x ); } public void show ( String s ) { System. out. println ( "Parent show with String: " + s ); } }

// Child class class Child extends Parent { // Method overriding @Override public void display () { System. out. println ( "Child's display" ); } // Method overloading (in child class) public void show ( double d ) { System. out. println ( "Child show with double: " + d ); } }

Line-by-line explanation:

1. class Parent - Defines parent class with polymorphic methods 2. public void display() - Method that will be overridden in child class 3. public void show(int x) - First overloaded version of show() 4. public void show(String s) - Second overloaded version

(compile-time polymorphism)

5. class Child extends Parent - Child class inheriting from Parent 6. @Override - Annotation indicating method overriding (optional but

recommended)

7. public void display() - Overridden method (runtime polymorphism) 8. public void show(double d) - New overloaded method in child class Multiple Examples (Beginner to Advanced) Example 1: Beginner Level - Basic Polymorphism java // Animal hierarchy example

Output Explanation:

text Dog barks: Woof! Woof! Cat meows: Meow! Meow! Playing Bell once Playing Drum 3 times

Real-life Analogy: Think of a universal remote control (Animal reference) that

can operate different devices (Dog, Cat objects). Pressing the "power" button

(makeSound()) performs different actions based on which device it's currently

pointing to.

Example 2: Intermediate Level - Bank System java // Banking system with different account types abstract class BankAccount { protected String accountNumber ; protected double balance ; public BankAccount ( String accountNumber , double balance ) { this. accountNumber = accountNumber ; this. balance = balance ; } // Abstract method - must be overridden public abstract double calculateInterest (); // Common method with polymorphism public void displayAccountInfo () { System. out. println ( "Account: " + accountNumber ); System. out. println ( "Balance: $" + balance ); System. out. println ( "Interest: $" + calculateInterest ()); } // Overloaded deposit methods

public void deposit ( double amount ) { balance += amount ; System. out. println ( "Deposited: $" + amount ); } public void deposit ( double amount , String description ) { balance += amount ; System. out. println ( "Deposited: $" + amount + " - " + description ); } } class SavingsAccount extends BankAccount { private static final double INTEREST_RATE = 0.04 ; public SavingsAccount ( String accountNumber , double balance ) { super ( accountNumber , balance ); } @Override public double calculateInterest () { return balance * INTEREST_RATE ; } // Additional method specific to SavingsAccount public void addBonus () { if ( balance > 5000 ) { balance += 50 ; System. out. println ( "$50 bonus added!" ); } } } class CurrentAccount extends BankAccount { private static final double INTEREST_RATE = 0.01 ; private double overdraftLimit ; public CurrentAccount ( String accountNumber , double balance , double overdraftLimit ) { super ( accountNumber , balance ); this. overdraftLimit = overdraftLimit ; } @Override public double calculateInterest () { return balance * INTEREST_RATE ; } // Overriding with additional functionality @Override public void displayAccountInfo () { super. displayAccountInfo ();

**_Account: SAV Balance: $3000. Interest: $120.


Deposited: $1000. Deposited: $500.0 - Gift from friend $50 bonus added! Example 3: Advanced Level - Shape Drawing with Interfaces java // Interface demonstrating polymorphism interface Drawable_** { void draw (); double getArea (); // Default method (Java 8+) - can be overridden default void displayInfo () { System. out. println ( "Drawing: " + this. getClass (). getSimpleName ()); } // Static method in interface static void printDrawingRules () { System. out. println ( "All drawings must implement draw() method" ); } } // Abstract class implementing interface abstract class Shape implements Drawable { protected String color ; public Shape ( String color ) { this. color = color ; } public String getColor () { return color ; } // Common implementation @Override public void displayInfo () { System. out. println ( "Color: " + color ); System. out. println ( "Area: " + getArea ());

// Concrete classes class Circle extends Shape { private double radius ; public Circle ( String color , double radius ) { super ( color ); this. radius = radius ; } @Override public void draw () { System. out. println ( "Drawing a " + color + " circle with radius " + radius ); } @Override public double getArea () { return Math. PI * radius * radius ; } // Overloaded constructor public Circle ( double radius ) { this ( "Black" , radius ); // Calling another constructor } } class Rectangle extends Shape { private double length ; private double width ; public Rectangle ( String color , double length , double width ) { super ( color ); this. length = length ; this. width = width ; } @Override public void draw () { System. out. println ( "Drawing a " + color + " rectangle " + length + "x" + width ); } @Override public double getArea () { return length * width ; } // Covariant return type example @Override

System. out. println ( "-------------------" ); } // Demonstrating instanceof with interfaces for ( Drawable drawing : drawings ) { if ( drawing instanceof Resizable ) { Resizable resizable = ( Resizable ) drawing ; resizable. printSize (); } } // Method overloading in action render ( drawings [ 0 ]); render ( drawings [ 1 ], "High Quality" ); } // Overloaded methods public static void render ( Drawable d ) { System. out. println ( "\nRendering in standard quality:" ); d. draw (); } public static void render ( Drawable d , String quality ) { System. out. println ( "\nRendering in " + quality + ":" ); d. draw (); } }

Output Explanation:

**_text All drawings must implement draw() method === Drawing All Shapes === Drawing a Red circle with radius 5. Color: Red Area: 78. HashCode: [some hashcode]


Drawing a Blue rectangle 4.0x6. Color: Blue Area: 24. HashCode: [some hashcode]


Drawing a Black circle with radius 3._**

**_Color: Black Area: 28. HashCode: [some hashcode]


Drawing a Green circle with radius 7. Color: Green Area: 153. HashCode: [some hashcode]


Advanced Circle size details Rendering in standard quality: Drawing a Red circle with radius 5. Rendering in High Quality: Drawing a Blue rectangle 4.0x6. Important Points for Exams Exam Notes - Must Remember!_**

● ✓ Polymorphism = Method Overloading (Compile-time) + Method

Overriding (Runtime)

● ✓ Reference type determines which overloaded method is called

(compile-time)

● ✓ Actual object type determines which overridden method is called

(runtime)

● ✓ Instance variables follow reference type, methods follow object type

(for overriding)

● ✓ Use @Override annotation to prevent accidental overloading instead

of overriding

● ✓ Constructor cannot be overridden (not inherited) but can be

overloaded

● ✓ private, final, and static methods cannot be overridden

● ✓ Covariant return types allowed from Java 5 (child class method can

return subclass of parent's return type)

● ✓ Abstract methods must be overridden in concrete subclasses

Frequently Asked Exam Facts

1. Can we override main() method? - No, main() is static

2. Can constructors be overridden? - No, constructors are not inherited

3. Can we override private methods? - No, private methods are not visible

to subclasses

4. Difference between method hiding and overriding? - Hiding: static

methods, compile-time; Overriding: instance methods, runtime

5. Can we achieve polymorphism without inheritance? - Yes, through

interfaces (interface polymorphism)

Solved Questions Short Answer Questions (3-5)

Q1: What is the difference between compile-time and runtime polymorphism?

Answer:

● Compile-time Polymorphism (Method Overloading):

○ Achieved through method overloading

○ Decision made at compile time

○ Multiple methods with same name but different parameters

○ Within same class or parent-child

○ Example: void print(int x) and void print(String s)

● Runtime Polymorphism (Method Overriding):

○ Achieved through method overriding

○ Decision made at runtime (Dynamic Method Dispatch)

○ Method in child class with same signature as parent

○ Requires inheritance relationship

○ Example: Animal a = new Dog(); a.sound();

Q2: Can we override static methods in Java? Explain.

Answer:

No, static methods cannot be overridden. They are associated with the class,

not instances. When a subclass defines a static method with the same signature

as parent class, it's called method hiding, not overriding. The method called

depends on the reference type, not the object type.

Q3: What is the purpose of @Override annotation?

Answer:

The @Override annotation:

1. Indicates the method is intended to override a parent class method

2. Provides compile-time checking - compiler verifies if method actually

overrides

3. Improves code readability

4. Prevents accidental overloading instead of overriding

5. Helps in maintenance by clearly showing overriding relationships

Q4: Explain covariant return types in method overriding.

Answer:

From Java 5 onwards, an overriding method can have a return type that is a

subclass of the return type of the overridden method. This is called covariant

return type.

java class Parent { Number getNumber () { return 1 ; } } class Child extends Parent { @Override Integer getNumber () { return 2 ; } // Integer extends Number }

Q5: What is Dynamic Method Dispatch?

Answer:

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

2. Runtime Polymorphism (Dynamic Binding):

● Achieved through Method Overriding

● Method in child class with same signature as parent class

● Resolution occurs at runtime (Dynamic Method Dispatch)

● Example:

● java

class Animal { void sound () { System. out. println ( "Animal sound" ); } } class Dog extends Animal { @Override void sound () { System. out. println ( "Bark" ); }

Rules and Differences:

Aspect Method Overloading Method Overriding

Relationship Same class or inheritance Only inheritance

Parameters Must be different Must be identical

Return type Can be different Must be same or covariant

Binding time Compile-time Runtime

Access modifier Can be different Cannot be more restrictive

Exceptions Can throw different Cannot throw broader

Real-World Applications:

1. Payment Processing: Single interface for different payment methods

2. Database Connectivity: Common API for different databases

3. GUI Frameworks: Component rendering based on actual object type

4. Plugin Architectures: Extensible systems through polymorphism

Conclusion: Polymorphism enhances code reusability, flexibility, and

maintainability, making it essential for large-scale Java applications.

Q2: Describe how polymorphism is implemented in Java Collections Framework

with examples. Discuss interfaces like List, Set, Map and their implementations.

Structured Answer:

Introduction:

Java Collections Framework extensively uses polymorphism through interfaces

and their implementations, providing flexibility and interchangeability.

Polymorphism in Collections:

1. List Interface and Implementations:

java List < String > list1 = new ArrayList <>(); // Polymorphic reference List < String > list2 = new LinkedList <>(); // Same interface, different implementation List < String > list3 = new Vector <>(); // Another implementation ● All share common List methods: add(), get(), remove()

● Different internal implementations

● Can switch implementations easily