Java Polymorphism

java

Polymorphism is a concept in object-oriented programming that refers to the ability of a single entity (such as a method or an object) to have multiple forms. In Java, polymorphism can be achieved through method overloading, method overriding, and inheritance.

Method overloading is a technique in which a class defines multiple methods with the same name, but different parameter lists. When a method is called, the Java compiler determines which version of the method to execute based on the number and type of arguments passed to the method.

Method overriding is a technique in which a subclass provides a new implementation for a method that is already defined in the superclass. When a method is called on an object, the version of the method that is executed is determined by the type of the object, not the type of the reference that points to the object.

Inheritance is a mechanism in which a subclass inherits the properties and methods of a superclass. A subclass can override the methods of its superclass by providing a new implementation for the method. When a method is called on an object, the version of the method that is executed is determined by the type of the object, not the type of the reference that points to the object.

Here’s an example of polymorphism in Java using method overloading and method overriding:

class Animal {
  public void makeSound() {
    System.out.println("Some generic animal sound");
  }
}

class Cat extends Animal {
  @Override
  public void makeSound() {
    System.out.println("Meow");
  }
}

class Dog extends Animal {
  @Override
  public void makeSound() {
    System.out.println("Bark");
  }
  
  public void makeSound(int numSounds) {
    for (int i = 0; i < numSounds; i++) {
      System.out.println("Bark");
    }
  }
}

In this example, the Cat and Dog classes both override the makeSound() method of the Animal class. The Dog class also has an overloaded version of the makeSound() method that takes an integer argument. When a makeSound() method is called on a Cat object, the version of the method in the Cat class will be executed, while when it is called on a Dog object, the version of the method in the Dog class will be executed, depending on the number and type of arguments passed to the method.