Sobes.tech
Middle

What mechanisms of polymorphism implementation exist in Java?

sobes.tech AI

Answer from AI

  • Compile-time polymorphism (static polymorphism): Implemented through method overloading. Methods have the same name but different signatures (number, type, or order of arguments).

    class Calculator {
        // Overloading the add method
        public int add(int a, int b) {
            return a + b;
        }
    
        public double add(double a, double b) {
            return a + b;
        }
    }
    
  • Runtime polymorphism (dynamic polymorphism): Implemented through method overriding. A method in a subclass has the same signature as in the parent class and provides its own implementation. The decision about which method to call is made at runtime depending on the actual object type.

    class Animal {
        public void sound() {
            System.out.println("Animal makes a sound");
        }
    }
    
    class Dog extends Animal {
        // Overriding the sound method
        @Override
        public void sound() {
            System.out.println("Dog barks");
        }
    }
    
    class Cat extends Animal {
        // Overriding the sound method
        @Override
        public void sound() {
            System.out.println("Cat meows");
        }
    }
    
  • References to superclass/interface: Subclass objects can be assigned to references of superclasses or interfaces they implement. This allows handling objects of different types uniformly through a common reference. Calling an overridden method through such a reference results in executing the method version from the actual object type.

    Animal myAnimal = new Dog(); // Assigning a Dog object to an Animal reference
    myAnimal.sound(); // Calls the overridden sound() method from the Dog class
    
What mechanisms of polymorphism implementation exist… - sobes.tech