What is polymorphism in Java and how is it achieved

Polymorphism is one of the four fundamental principles of object-oriented programming (OOP) and is a key feature in Java. It allows objects of different classes to be treated as objects of a common superclass during runtime, providing a unified interface for different classes. Polymorphism enables flexibility and extensibility in your code, making it easier to add new classes or behavior without modifying existing code.

In Java, polymorphism is achieved through two mechanisms:

  1. Method Overriding (Run-time Polymorphism): Method overriding allows a subclass to provide a specific implementation of a method that is already defined in its superclass. When a method is called on an object, Java will look for the most specific implementation of that method in the object's class hierarchy. If an overriding method is found in the subclass, it will be executed instead of the method in the superclass. The method signature (name, parameters, and return type) must be the same in both the superclass and subclass.

    Here's an example of method overriding in Java:

    
     

    javaCopy code

    class Animal { void sound() { System.out.println("Animal makes a sound."); } } class Dog extends Animal { @Override void sound() { System.out.println("Dog barks."); } } public class Main { public static void main(String[] args) { Animal animal = new Dog(); // Polymorphism: Dog is treated as an Animal animal.sound(); // Output: Dog barks. } }

  2. Method Overloading (Compile-time Polymorphism): Method overloading allows multiple methods with the same name but different parameters (number or type) to coexist within a class. When a method is called, Java determines which overloaded method to execute based on the number and types of arguments passed to the method at compile time.

    Here's an example of method overloading in Java:

    
     

    javaCopy code

    class MathOperations { int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } } public class Main { public static void main(String[] args) { MathOperations math = new MathOperations(); System.out.println(math.add(5, 10)); // Output: 15 (int version of add is called) System.out.println(math.add(3.5, 2.5)); // Output: 6.0 (double version of add is called) } }

In both cases, the specific implementation of the method to be executed is determined either at runtime (method overriding) or at compile time (method overloading) based on the reference type or the arguments passed to the method, respectively. This ability to treat objects of different classes as objects of a common superclass is the essence of polymorphism in Java.

Top Countries For What is polymorphism in Java and how is it achieved

Top Services From What is polymorphism in Java and how is it achieved

Top Keywords From What is polymorphism in Java and how is it achieved