Polymorphism in Java

What is Polymorphism and it’s types in Java

In this article, we’ll cover the most asked interview questions in java

E.g:

What is Polymorphism
What are the types of polymorphism
differences between method overloading and method overriding


What is Polymorphism in Java

Polymorphism in Java is the task that performs a single action in different ways.

So, languages that do not support polymorphism are not ‘Object-Oriented Languages’, but ‘Object-Based Languages’. Ada, for instance, is one such language. Since Java supports polymorphism, it is an Object Oriented Language.

Polymorphism in Java is the ability of a single method or class to take on multiple forms. It allows objects of different types to be treated as objects of a common type, providing a way to achieve flexibility and abstraction in programming. Polymorphism is achieved through two mechanisms in Java: method overloading and method overriding.

1. Method Overloading:

  • Method overloading is a form of compile-time (static) polymorphism, where multiple methods with the same name are defined within a class, but they differ in their parameter types, number of parameters, or both.
  • The compiler determines which method to invoke based on the method signature during compile-time.

Example
public class MathOperations {
    // Method to add two integers
    public int add(int a, int b) {
        return a + b;
    }

    // Method to add three integers
    public int add(int a, int b, int c) {
        return a + b + c;
    }

    // Method to concatenate two strings
    public String add(String str1, String str2) {
        return str1 + str2;
    }

    public static void main(String[] args) {
        MathOperations math = new MathOperations();

        // Method overloading based on parameters
        System.out.println(math.add(2, 3));
        System.out.println(math.add(2, 3, 4));
        System.out.println(math.add("Hello", "World"));
    }
}

2. Method Overriding:

  • Method overriding is a form of run-time (dynamic) polymorphism, where a subclass provides a specific implementation for a method that is already defined in its superclass.
  • The decision of which method to call is made at runtime based on the actual type of the object.

Polymorphism in Java
Example
// Parent class
class Animal {
    void makeSound() {
        System.out.println("Animal makes a sound");
    }
}

// Subclass overriding the makeSound method
class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("Dog barks");
    }
}

// Subclass overriding the makeSound method
class Cat extends Animal {
    @Override
    void makeSound() {
        System.out.println("Cat meows");
    }
}

public class PolymorphismExample {
    public static void main(String[] args) {
        Animal myAnimal;

        // Polymorphic behavior based on the actual type of the object
        myAnimal = new Dog();
        myAnimal.makeSound(); // Calls the overridden method in Dog

        myAnimal = new Cat();
        myAnimal.makeSound(); // Calls the overridden method in Cat
    }
}

In this example, the makeSound method is overridden in the Dog and Cat subclasses, providing a different implementation for each. At runtime, the actual type of the object determines which version of the method is called.

Polymorphism allows for more flexible and extensible code by enabling code to work with objects of multiple types in a unified manner. It enhances the readability, maintainability, and scalability of the code.


What are the types of polymorphism in java

Polymorphism in Java is the task that performs a single action in different ways.

So, languages that do not support polymorphism are not ‘Object-Oriented Languages’, but ‘Object-Based Languages’. Ada, for instance, is one such language. Since Java supports polymorphism, it is an Object Oriented Language.

Polymorphism in Java is the ability of a single method or class to take on multiple forms. It allows objects of different types to be treated as objects of a common type, providing a way to achieve flexibility and abstraction in programming. Polymorphism is achieved through two mechanisms in Java: method overloading and method overriding.

types of polymorphism in java

In Java, polymorphism is achieved through two main types: compile-time polymorphism (also known as static or method overloading) and runtime polymorphism (also known as dynamic or method overriding). Let’s explore both types in detail:

Polymorphism in Java

1. Compile-Time Polymorphism (Method Overloading):

  • Method Overloading: It involves defining multiple methods with the same name in the same class, but with different parameter types, number of parameters, or both.
  • operator overloading: Operator overloading in Java refers to the ability to define and use operators in a way that extends their functionality beyond their standard behavior. Unlike some other programming languages like C++, Java does not support operator overloading for custom classes. However, Java does have a set of predefined operators that can be used with built-in types.

Example of ‘Method Overloading’

Example
public class MathOperations {
  // Method to add two integers
  public int add(int a, int b) {
    return a + b;
  }

  // Method overloading to add three integers
  public int add(int a, int b, int c) {
    return a + b + c;
  }

  // Method overloading to concatenate two strings
  public String add(String str1, String str2) {
    return str1 + str2;
  }
  public static void main(String[] args) {
    MathOperations math = new MathOperations();
    System.out.println(math.add(2, 3)); // Calls the first method
    System.out.println(math.add(2, 3, 4)); // Calls the second method
    System.out.println(math.add("Hello", "World")); // Calls the third method
  }
}

Example of ‘Operator Overloading

Example
public class Addition {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        int c = a + b;
        System.out.println(c);  // 30
    }
}

2. Runtime Polymorphism (Method Overriding):

  • Method Overriding: It involves providing a specific implementation for a method in a subclass that is already defined in its superclass.
  • Determined at Runtime: The decision about which method to call is made at runtime based on the actual type of the object. It is also known as late or dynamic binding.

Example:

Example
// Parent class
class Animal {
    void makeSound() {
        System.out.println("Animal makes a sound");
    }
}

// Subclass overriding the makeSound method
class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("Dog barks");
    }
}

// Subclass overriding the makeSound method
class Cat extends Animal {
    @Override
    void makeSound() {
        System.out.println("Cat meows");
    }
}

Usage:

Example
Animal myAnimal;

// Polymorphic behavior based on the actual type of the object
myAnimal = new Dog();
myAnimal.makeSound(); // Calls the overridden method in Dog

myAnimal = new Cat();
myAnimal.makeSound(); // Calls the overridden method in Cat

Note: Runtime polymorphism is achieved through the use of the @Override annotation to indicate that a method in a subclass is intended to override a method in its superclass.

Both compile-time polymorphism (method overloading) and runtime polymorphism (method overriding) contribute to the concept of polymorphism in Java, allowing for flexibility and abstraction in object-oriented programming.


What are differences between method overloading and method overriding in java

Method overloading and method overriding are two important concepts in Java related to polymorphism. Let’s compare them in terms of their definitions, use cases, and characteristics:

Polymorphism in Java

Method Overloading:

1. Definition: Method overloading occurs when a class has multiple methods with the same name but different parameter lists (different types or different numbers of parameters).

2. Syntax: The methods must have the same name but differ in the number or types of parameters.

3. Use Cases:

  • Providing multiple ways to perform a similar operation with different parameter sets.
  • Enhancing readability and maintainability by using the same method name for related operations.

4. Decision Time: Decided at compile time (compile-time polymorphism or static polymorphism).

Example:

Example
public class MathOperations {
    public int add(int a, int b) {
        return a + b;
    }

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

    public String concatenate(String str1, String str2) {
        return str1 + str2;
    }
}

Usage:

Example
MathOperations math = new MathOperations();
int result1 = math.add(2, 3);           // Calls the first method
double result2 = math.add(2.5, 3.5);    // Calls the second method
String result3 = math.concatenate("Hello", "World");

Method Overriding:

1. Definition: Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass.

2. Syntax: The subclass method must have the same signature (name, return type, and parameters) as the superclass method.

3. Use Cases:

  • Modifying or extending the behavior of a method in a subclass.
  • Achieving polymorphic behavior through dynamic method dispatch.

4. Decision Time: Decided at runtime (run-time polymorphism or dynamic polymorphism).

Example:

Example
// Parent class
class Animal {
    void makeSound() {
        System.out.println("Animal makes a sound");
    }
}

// Subclass overriding the makeSound method
class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("Dog barks");
    }
}

Usage:

Example
Animal myAnimal = new Dog();
myAnimal.makeSound();  // Calls the overridden method in Dog

Key Differences:

FeatureMethod OverloadingMethod Overriding
OccurrenceWithin the same class.Between a superclass and its subclass.
SyntaxDifferent parameter lists or types.Same signature (name, return type, parameters).
Decision TimeCompile time (static polymorphism).Runtime (dynamic polymorphism).
Use CasesProviding multiple versions of a method with different parameters.Modifying or extending the behavior of a method in a subclass.
Examplejava public int add(int a, int b) { //... } public double add(double a, double b) { //... }java class Animal { void makeSound() { //... } } class Dog extends Animal { @Override void makeSound() { //... } }
BindingStatic binding.Dynamic binding.
Object TypeSame class or same hierarchy.Subclass object referring to a superclass object (polymorphism).

In summary, method overloading involves multiple methods within the same class, distinguished by different parameter lists, and is resolved at compile time. Method overriding occurs in a subclass, providing a specific implementation for a method in the superclass, and is resolved at runtime. Both concepts contribute to the flexibility and versatility of object-oriented programming in Java.

Leave a Reply

Your email address will not be published. Required fields are marked *