Polymorphism - 3 | Chapter 12: Inheritance, Interface, and Polymorphism | ICSE Class 12 Computer Science
Students

Academic Programs

AI-powered learning for grades 8-12, aligned with major curricula

Professional

Professional Courses

Industry-relevant training in Business, Technology, and Design

Games

Interactive Games

Fun games to boost memory, math, typing, and English skills

Polymorphism

3 - Polymorphism

Enroll to start learning

You’ve not yet enrolled in this course. Please enroll for free to listen to audio lessons, classroom podcasts and take practice test.

Practice

Interactive Audio Lesson

Listen to a student-teacher conversation explaining the topic in a relatable way.

Introduction to Polymorphism

πŸ”’ Unlock Audio Lesson

Sign up and enroll to listen to this audio lesson

0:00
--:--
Teacher
Teacher Instructor

Today, we will explore polymorphism. Can anyone tell me what that term might mean?

Student 1
Student 1

It sounds like it means many forms.

Teacher
Teacher Instructor

Exactly, polymorphism means 'many forms'. In Java, this allows an object to be treated as an instance of its superclass. Very useful, right? Think of it as a flexible way to interact with different objects.

Student 2
Student 2

Can you give us an example?

Teacher
Teacher Instructor

Sure! For instance, if we have a class `Animal`, and both `Cat` and `Dog` extend it, we call a method like `sound()` on an `Animal` type variable referencing a `Cat`. It will call the `Cat's` implementation, not the `Animal's`.

Student 3
Student 3

That's interesting! So, it's about having one method work for different types?

Teacher
Teacher Instructor

Right! Remember, polymorphism is powerful because it reduces complexity and increases the flexibility of the code.

Teacher
Teacher Instructor

To recap, polymorphism allows for a single interface to represent different underlying forms, enhancing code reusability.

Compile-time Polymorphism

πŸ”’ Unlock Audio Lesson

Sign up and enroll to listen to this audio lesson

0:00
--:--
Teacher
Teacher Instructor

Now, let's dive deeper into compile-time polymorphism. Who remembers what method overloading is?

Student 2
Student 2

It's when multiple methods in the same class have the same name but different parameters.

Teacher
Teacher Instructor

Correct! For instance, in our `Calculator` class, if we have `add(int a, int b)` and `add(int a, int b, int c)`, that's a classic case of method overloading.

Student 4
Student 4

So, the method chosen depends on the arguments provided?

Teacher
Teacher Instructor

Exactly! This is great for methods like addition where the number of inputs can vary. Can anyone think of another scenario for overloading?

Student 1
Student 1

Maybe for a method that prints different types of messages?

Teacher
Teacher Instructor

Good thought! You can overload methods for different data types or formats. This technique simplifies our code significantly.

Teacher
Teacher Instructor

In summary, compile-time polymorphism allows methods to be flexible depending on input parameters, enhancing code readability.

Runtime Polymorphism

πŸ”’ Unlock Audio Lesson

Sign up and enroll to listen to this audio lesson

0:00
--:--
Teacher
Teacher Instructor

Moving on, let's discuss runtime polymorphism, also known as method overriding. Who can explain what that is?

Student 3
Student 3

Isn’t it when an extended class provides a specific implementation of a method from its parent class?

Teacher
Teacher Instructor

Spot on! The method in the subclass must have the same name, return type, and parameters as the one in the superclass. For example, `sound()` from `Animal` can be overridden in the `Cat` class to change its behavior.

Student 2
Student 2

Why do we call this runtime polymorphism?

Teacher
Teacher Instructor

Because the method that gets invoked is determined at runtime based on the actual object type. This supports dynamic method dispatch. Understanding this allows for more flexible program designs.

Student 4
Student 4

So, even if we reference `Cat` as `Animal`, we still call the `Cat's` implementation?

Teacher
Teacher Instructor

Exactly! It allows us to treat different objects uniformly while accessing relevant behaviors.

Teacher
Teacher Instructor

In conclusion, runtime polymorphism enhances program flexibility by allowing method functionality to be defined and altered across different classes.

Introduction & Overview

Read summaries of the section's main ideas at different levels of detail.

Quick Overview

Polymorphism in Java allows objects to operate in multiple forms, enhancing flexibility and enabling method overloading and overriding.

Standard

In Java, polymorphism is a core concept allowing a single interface to represent different underlying data types. It comprises compile-time polymorphism (method overloading) and runtime polymorphism (method overriding) to promote flexible coding practices.

Detailed

Polymorphism

Polymorphism, derived from the Greek words 'poly' meaning many and 'morph' meaning forms, is a fundamental principle in object-oriented programming that allows objects to be treated as instances of their parent class. In Java, polymorphism mainly comes in two forms: compile-time and runtime.

Key Types of Polymorphism in Java:

  1. Compile-time Polymorphism (Method Overloading): This occurs when two or more methods in the same class share the same name but differ in parameters, such as number or type of parameters.
  2. Example: A Calculator class can have overloaded methods for adding different numbers of integers.
  3. Runtime Polymorphism (Method Overriding): This takes place when a subclass alters a method's behavior defined in its superclass. The choice of which method to invoke is determined at runtime based on the object type.
  4. Example: An Animal class may have a method sound(), which a Cat class overrides to provide a specific implementation.

Understanding polymorphism is crucial as it promotes flexibility and reusability in code, allowing developers to define methods that handle multiple formats and behaviors. This ultimately leads to better-organized and maintainable code.

Audio Book

Dive deep into the subject with an immersive audiobook experience.

What is Polymorphism?

Chapter 1 of 3

πŸ”’ Unlock Audio Chapter

Sign up and enroll to access the full audio experience

0:00
--:--

Chapter Content

Polymorphism means "many forms". In Java, polymorphism allows objects to be treated as instances of their parent class rather than their actual class. There are two types of polymorphism in Java:
- Compile-time polymorphism (Method Overloading)
- Runtime polymorphism (Method Overriding)

Detailed Explanation

Polymorphism is a foundational concept in object-oriented programming that enables a single interface to represent different underlying forms. This means that a child class object can be used wherever a parent class object is expected, enhancing flexibility and functionality. In Java, polymorphism can occur in two forms: compile-time and runtime.

  • Compile-time polymorphism, known as method overloading, happens when two or more methods in the same class have the same name but differ in their parameter lists. For instance, you could have an 'add' method that adds numbers, but it could accept different numbers of input parameters: two numbers or three.
  • Runtime polymorphism, known as method overriding, takes place when a subclass provides a specific implementation for a method that already exists in its superclass. This allows the program to decide which method implementation to execute at runtime based on the object instance.

Examples & Analogies

Think of a polymorphic program like a multi-tool device, such as a Swiss Army knife. Just as this tool can take on many functionsβ€”like a knife, a screwdriver, or scissorsβ€”polymorphism allows objects to take multiple forms based on their context. For instance, a 'Vehicle' can be a car or a truck, where both can handle the same basic functions, such as 'move' or 'stop', but implement those functions in ways that suit their specific characteristics.

Compile-time Polymorphism (Method Overloading)

Chapter 2 of 3

πŸ”’ Unlock Audio Chapter

Sign up and enroll to access the full audio experience

0:00
--:--

Chapter Content

Method overloading occurs when multiple methods in the same class have the same name but different parameters (different type or number).
Example:

class Calculator {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
public class TestOverloading {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(5, 10)); // Output: 15
System.out.println(calc.add(5, 10, 15)); // Output: 30
}
}

Detailed Explanation

Compile-time polymorphism, or method overloading, occurs when you have multiple methods in the same class bearing the same name but varying in their type or number of parameters. The Java compiler determines which method to execute based on the arguments passed when the method is called. In the provided example, the 'Calculator' class contains two 'add' methods: one that takes two integers and another that takes three integers. When you call 'calc.add(5, 10)', the compiler knows to use the first 'add' method; for 'calc.add(5, 10, 15)', it selects the second.

This mechanism promotes code readability and usability because it allows a single method name to perform a variety of tasks depending on the inputs it is given.

Examples & Analogies

Consider a utility knife that has different blades for various situations. One blade could be designed for slicing bread, while another handles delicate vegetables. Similarly, method overloading allows you to use the same method name for different contexts and inputs, enhancing the flexibility and usability of your code.

Runtime Polymorphism (Method Overriding)

Chapter 3 of 3

πŸ”’ Unlock Audio Chapter

Sign up and enroll to access the full audio experience

0:00
--:--

Chapter Content

Method overriding happens when a subclass provides a specific implementation for a method already defined in its superclass. The method in the subclass should have the same name, return type, and parameters.
At runtime, Java determines which method to call based on the actual object type (dynamic method dispatch).
Example:

class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Cat extends Animal {
void sound() {
System.out.println("Cat meows");
}
}
public class TestOverriding {
public static void main(String[] args) {
Animal a = new Cat();
a.sound(); // Output: Cat meows
}
}

Detailed Explanation

Runtime polymorphism, also known as method overriding, occurs when a subclass provides a concrete implementation of a method that is declared in the superclass. The overriding method must have the same name, parameters, and return type as the original method. With this mechanism, when you create an object of the subclass and call the overridden method, Java uses the actual object's class at runtime to determine which method to execute. In the example, while the reference type is 'Animal', the actual object is a 'Cat'. When 'a.sound()' is called, the 'Cat' class's implementation of 'sound()' is executed instead of the 'Animal' class's implementation.

This dynamic method dispatch mechanism enhances flexibility because you can write programs that work on the superclass type while still exhibiting subclass specific behavior.

Examples & Analogies

Imagine a remote control for various devices in your home. When you press the 'play' button, your remote activates the specific device that is currently selectedβ€”like a DVD player, a streaming box, or a music player. Depending on which device is in focus, the play action performs differently. Similarly, method overriding allows the same method call to produce different behaviors depending on the object it's acting upon.

Key Concepts

  • Polymorphism: Refers to the ability of an object to take on many forms via method overloading and overriding.

  • Compile-time Polymorphism: Achieved through method overloading; methods in the same class have the same name but different parameters.

  • Runtime Polymorphism: Achieved through method overriding; allows a subclass to redefine a superclass method.

  • Dynamic Method Dispatch: Refers to the method resolution happening at runtime, allowing behavior customization.

Examples & Applications

Example of Compile-time Polymorphism: In a Calculator class, having methods add(int a, int b) and add(double a, double b) demonstrates method overloading.

Example of Runtime Polymorphism: Given an Animal class with a method sound(), a subclass Dog overriding this method to provide 'Bark' demonstrates runtime polymorphism.

Memory Aids

Interactive tools to help you remember key concepts

🎡

Rhymes

Polymorphism lets types shine, one method functions in many lines.

πŸ“–

Stories

Imagine a toolbox where the same tool adaptsβ€”like a Swiss Army knifeβ€”for different tasks, just like polymorphism offers different behaviors through the same interface.

🧠

Memory Tools

POM: Polymorphism Overloads Method.

🎯

Acronyms

POC

Polymorphism Offers Choice.

Flash Cards

Glossary

Polymorphism

The ability of an object to take on many forms; in Java, referring specifically to method overloading and overriding.

Method Overloading

A feature that allows a class to have multiple methods with the same name but differing parameter types or counts.

Method Overriding

A feature that allows a subclass to provide a specific implementation for a method already defined in its superclass.

Dynamic Method Dispatch

The process of selecting which method to call at runtime based on the object type.

Reference links

Supplementary resources to enhance your learning experience.