java
  1. java-polymorphism

Java Polymorphism

Syntax

public class Animal {
   public void makeSound() {
      System.out.println("Animal makes a sound");
   }
}
public class Dog extends Animal {
   public void makeSound() {
      System.out.println("Dog barks");
   }
}
public class Main {
   public static void main(String[] args) {
      Animal myAnimal = new Animal();
      Animal myDog = new Dog();
      myAnimal.makeSound();
      myDog.makeSound();
   }
}

Example

Creating a superclass Animal and a subclass Dog to demonstrate polymorphism in Java.

Output

Animal makes a sound
Dog barks

Explanation

In Java, polymorphism is the ability of an object to take on many forms. This means that a single object can be referred to as multiple types. It is achieved through inheritance and method overriding.

In the above example, Animal is the superclass and Dog is the subclass. Both classes have a method named makeSound(). However, the implementation is different in both classes. The Animal class has a generic implementation, while the Dog class has a specific implementation for barking.

In the Main class, we create two objects: myAnimal of type Animal and myDog of type Dog. When we call the makeSound() method on each object, the output is different based on the object type. This is an example of polymorphism in Java, where a single method call can result in different behavior based on the type of the object.

Use

Polymorphism is an important concept in Java programming as it allows for more efficient and flexible code. It can simplify code by removing the need for multiple conditional statements and allows for easier maintenance of the code. Polymorphism is commonly used in object-oriented design patterns and frameworks.

Important Points

  • Polymorphism is the ability of an object to take on many forms.
  • Polymorphism is achieved through inheritance and method overriding.
  • Polymorphism can simplify code and allows for more efficient and flexible code.
  • Polymorphism is commonly used in object-oriented design patterns and frameworks.

Summary

Polymorphism is an important concept in Java programming that allows a single object to be referred to as multiple types. It is achieved through inheritance and method overriding. Polymorphism can simplify code and allows for more efficient and flexible code. It is commonly used in object-oriented design patterns and frameworks.

Published on: