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
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?