0% found this document useful (0 votes)
2 views12 pages

Polymorphism.java

Polymorphism in Java allows methods or objects to behave differently based on the context, with two main types: compile-time (method overloading) and runtime (method overriding). Compile-time polymorphism occurs when multiple methods have the same name but different parameters, while runtime polymorphism allows a child class to provide its own implementation of a method defined in a parent class. This concept enhances flexibility and reusability in programming, enabling dynamic method dispatch based on the actual object type at runtime.
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)
2 views12 pages

Polymorphism.java

Polymorphism in Java allows methods or objects to behave differently based on the context, with two main types: compile-time (method overloading) and runtime (method overriding). Compile-time polymorphism occurs when multiple methods have the same name but different parameters, while runtime polymorphism allows a child class to provide its own implementation of a method defined in a parent class. This concept enhances flexibility and reusability in programming, enabling dynamic method dispatch based on the actual object type at runtime.
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

What is Polymorphism?

Poly = Many
Morph = Forms

Definition:
Polymorphism is the ability of one method or one object to behave in different ways.

In Java, the same method name can perform different actions depending on the situation.

Real-Life Example

Think about the Power Button on different devices.

• Phone → Locks screen

• Laptop → Sleep/Shutdown options

• TV Remote → Turns TV ON/OFF

Same button, different behavior.

This is Polymorphism.

Types of Polymorphism

Java supports two types:

1. Compile-Time Polymorphism

o Method Overloading

2. Runtime Polymorphism

o Method Overriding

1. Method Overloading (Compile-Time Polymorphism)

Definition

Method Overloading means having multiple methods with the same name but different parameters
in the same class.

The compiler decides which method to call.

Hence it is called Compile-Time Polymorphism.

Rules

✔ Same method name

✔ Different parameter list

• Different number of parameters


• Different types

• Different order of parameters

Return type alone cannot overload a method.

Example 1

class Calculator {

int add(int a, int b) {


return a + b;
}

int add(int a, int b, int c) {


return a + b + c;
}

public static void main(String[] args) {

Calculator c = new Calculator();

[Link]([Link](5, 6));
[Link]([Link](5, 6, 7));
}
}

Output

11
18

Example 2

class Print {

void show(int a) {
[Link]("Integer : " + a);
}

void show(String name) {


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

public static void main(String[] args) {

Print p = new Print();


[Link](10);
[Link]("David");
}
}

Output

Integer : 10
String : David

Invalid Overloading

This is not allowed.

int add(int a, int b) { }

double add(int a, int b) { }

Why?

Because Java identifies methods using

• Method Name

• Parameter List

Return type is not considered.

Compile-Time Polymorphism

The compiler knows exactly which method to execute before running the program.

Example:

Calculator c = new Calculator();

[Link](2,3);

The compiler immediately knows:

add(int,int)

No guessing is needed during execution.


2. Method Overriding (Runtime Polymorphism)

Definition

Method Overriding happens when a child class provides its own implementation of a method already
defined in the parent class.

Example

class Animal {

void sound() {
[Link]("Animal Sound");
}
}

class Dog extends Animal {

@Override
void sound() {
[Link]("Bark");
}
}

public class Main {

public static void main(String[] args) {

Dog d = new Dog();

[Link]();
}
}

Output

Bark

The child method replaces the parent version.


Another Example

class Bird {

void fly() {
[Link]("Bird can fly");
}
}

class Eagle extends Bird {

@Override
void fly() {
[Link]("Eagle flies high");
}
}

public class Main {

public static void main(String[] args) {

Eagle e = new Eagle();

[Link]();
}
}

Output

Eagle flies high

Why Override?

Suppose every animal has a sound.

Parent class:

class Animal {

void sound() {
[Link]("Some Sound");
}
}

Dog:
class Dog extends Animal {

void sound() {
[Link]("Bark");
}
}

Cat:

class Cat extends Animal {

void sound() {
[Link]("Meow");
}
}

Cow:

class Cow extends Animal {

void sound() {
[Link]("Moo");
}
}

Each animal has its own implementation.

@Override Annotation

@Override
void sound() {

This tells Java:

"I am overriding a parent method."

Benefits:

• Prevents spelling mistakes

• Compiler checks correctness

• Improves readability

Rules for Method Overriding

✔ Same method name

✔ Same parameters
✔ Child class inherits parent

✔ Return type should be same (or covariant)

✔ Cannot reduce access level

Example:

Parent

public void display()

Child

public void display()

Allowed.

Not allowed

Parent

public void display()

Child

private void display()

Runtime Polymorphism

This is where Java becomes powerful.

Instead of

Dog d = new Dog();

we write

Animal a = new Dog();

Question:

Which method executes?

Animal?
or
Dog?

Answer:

Dog's method.

Because the actual object is Dog.


Example

class Animal {

void sound() {
[Link]("Animal");
}
}

class Dog extends Animal {

@Override
void sound() {
[Link]("Bark");
}
}

public class Main {

public static void main(String[] args) {

Animal a = new Dog();

[Link]();
}
}

Output

Bark

Although the reference is Animal, the object is Dog, so Java calls the overridden Dog method.

Why is it called Runtime Polymorphism?

The compiler only knows

Animal a

At runtime,

new Dog()

is created.

Java checks the actual object and calls the correct method.

Hence it is called Runtime Polymorphism.


Dynamic Method Dispatch

Definition

Dynamic Method Dispatch is the mechanism by which Java decides at runtime which overridden
method to execute based on the actual object, not the reference type.

Example

class Animal {

void sound() {
[Link]("Animal");
}
}

class Dog extends Animal {

@Override
void sound() {
[Link]("Bark");
}
}

class Cat extends Animal {

@Override
void sound() {
[Link]("Meow");
}
}

public class Main {

public static void main(String[] args) {

Animal a;

a = new Dog();
[Link]();

a = new Cat();
[Link]();
}
}

Output
Bark
Meow

The same reference variable (Animal a) points to different objects, and Java dynamically chooses the
appropriate overridden method at runtime.

Compile-Time vs Runtime Polymorphism

Feature Compile-Time Runtime

Achieved By Method Overloading Method Overriding

Decision Made During compilation During execution

Inheritance Required No Yes

Speed Faster Slightly slower

Example add(int,int) Animal a = new Dog();

Overloading vs Overriding

Method Overloading Method Overriding

Same class Parent and child classes

Same method name Same method name

Different parameters Same parameters

Compile-time Runtime

Inheritance not required Inheritance required

Problem 1: Method Overloading

Create a Calculator class with overloaded multiply() methods:

• Multiply two integers.

• Multiply three integers.

• Multiply two doubles.

Problem 2: Method Overloading

Create a Printer class with overloaded print() methods to display:


• An integer.

• A string.

• A boolean value.

Problem 3: Method Overriding

Create a parent class Shape with a method draw(). Create child classes Circle and Rectangle that
override draw().

Expected Output

Drawing Circle
Drawing Rectangle

Problem 4: Runtime Polymorphism

Create a parent class Employee with a method work(). Create child classes Developer and Manager
that override work(). Use an Employee reference to call each child's work() method.

Expected Output

Writing Code
Managing Team

Problem 5: Dynamic Method Dispatch

Create a parent class Payment with a method pay(). Create child classes CreditCard and UPI that
override pay(). Use a single Payment reference to point to both objects one after another and invoke
pay().

Expected Output

Payment through Credit Card


Payment through UPI
Problem Statement

Create a parent class named Vehicle with a method named start() that displays a general message
indicating that a vehicle is starting.

Create two child classes named Car and Bike that inherit from the Vehicle class.

Requirements

1. In the Vehicle class:

o Create a method start().

2. In the Car class:

o Override the start() method to display a message specific to a car.

o Overload the start() method by creating another version that accepts a String mode
parameter (for example, "Sport" or "Eco").

3. In the Bike class:

o Override the start() method to display a message specific to a bike.

o Overload the start() method by creating another version that accepts a String mode
parameter.

4. In the main() method:

o Use a Vehicle reference to demonstrate runtime polymorphism by assigning it first


to a Car object and then to a Bike object, calling the start() method each time.

o Create Car and Bike objects to call the overloaded start(String mode) methods.

Expected Output

Car Starts
Car Starts in Sport mode
Bike Starts
Bike Starts in Eco mode

You might also like