Site icon SATMMER

Polymorphism in Java

Polymorphism in Java

Polymorphism, a core concept in object-oriented programming (OOP), allows objects of different classes to be treated as objects of a common superclass. It promotes flexibility, extensibility, and the ability to write more generic and reusable code. In this article, we’ll explore the principles of polymorphism in Java, providing examples to illustrate its usage.

1. Understanding Polymorphism:

Polymorphism is derived from the Greek words “poly,” meaning many, and “morph,” meaning forms. In Java, polymorphism enables a single interface or method to be used for objects of various types.

// Superclass
class Shape {
void draw() {
System.out.println(“Drawing a shape.”);
}
}

// Subclasses
class Circle extends Shape {
@Override
void draw() {
System.out.println(“Drawing a circle.”);
}
}

class Square extends Shape {
@Override
void draw() {
System.out.println(“Drawing a square.”);
}
}

Highlights:

2. Compile-Time Polymorphism (Method Overloading):

Compile-time polymorphism, also known as method overloading, occurs when multiple methods in the same class have the same name but different parameters.

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

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

Highlights:

3. Runtime Polymorphism (Method Overriding):

Runtime polymorphism, or method overriding, allows a subclass to provide a specific implementation for a method that is already defined in its superclass.

class Animal {
void makeSound() {
System.out.println(“Some generic sound.”);
}
}

class Dog extends Animal {
@Override
void makeSound() {
System.out.println(“Bark! Bark!”);
}
}

Highlights:

4. Polymorphism with Interfaces:

Interfaces in Java provide a way to achieve polymorphism by allowing multiple classes to implement the same interface.

// Interface
interface Eater {
void eat();
}

// Implementing classes
class Lion implements Eater {
@Override
public void eat() {
System.out.println(“Lion is eating.”);
}
}

class Rabbit implements Eater {
@Override
public void eat() {
System.out.println(“Rabbit is eating.”);
}
}

Highlights:

5. The instanceof Operator:

The instanceof operator is used to test if an object is an instance of a particular class or interface.

Shape shape = new Circle();

if (shape instanceof Circle) {
Circle circle = (Circle) shape;
// Additional operations specific to Circle
}

Highlights:

6. Key Concepts:

a. Upcasting and Downcasting:

b. Abstract Classes and Polymorphism:

7. Conclusion:

Polymorphism is a powerful concept in Java that enhances code flexibility and encourages the creation of robust and extensible software. Whether through method overriding, interfaces, or method overloading, polymorphism enables developers to write code that adapts to different scenarios and supports code reuse. Understanding and embracing polymorphism is essential for creating modular, maintainable, and scalable Java applications.

Exit mobile version