How has polymorphism changed in recent Java versions?

Polymorphism in Java allows methods to do different things based on the object that it is acting on, even if they share the same name. There have been enhancements in recent Java versions, particularly with the introduction of features like Lambdas and functional interfaces, which have changed how polymorphism is viewed and implemented in Java.

Prior to Java 8, polymorphism was mainly achieved through method overriding and interfaces. However, with the introduction of Lambda expressions in Java 8, developers can implement behavior that can be passed around as code, effectively showcasing polymorphic behavior in a more concise manner.

Below is an example demonstrating polymorphism using interfaces and lambda expressions:

interface Animal { void sound(); } class Dog implements Animal { public void sound() { System.out.println("Woof"); } } class Cat implements Animal { public void sound() { System.out.println("Meow"); } } public class Main { public static void main(String[] args) { Animal myDog = new Dog(); Animal myCat = new Cat(); myDog.sound(); // Outputs: Woof myCat.sound(); // Outputs: Meow } }

polymorphism Java 8 lambda expressions functional interfaces method overriding