explain polymorphism in java with an example
- User
explain polymorphism in java with an example
Assistant
Polymorphism in Java allows objects of different classes to be treated as objects of a common superclass. It enables a single interface to represent different underlying forms (implementations).
Here's a simple example:
// Parent class class Animal { public void makeSound() { System.out.println("Some generic animal sound"); } } // Child classes class Dog extends Animal { @Override public void makeSound() { System.out.println("Woof woof!"); } } class Cat extends Animal { @Override public void makeSound() { System.out.println("Meow!"); } } // Main class to demonstrate polymorphism public class PolymorphismDemo { public static void main(String[] args) { // Animal reference, but Dog object Animal myDog = new Dog(); // Animal reference, but Cat object Animal myCat = new Cat(); // Animal reference, Animal object Animal myAnimal = new Animal(); // The same method call behaves differently based on the actual object type myDog.makeSound(); // Outputs: Woof woof! myCat.makeSound(); // Outputs: Meow! myAnimal.makeSound(); // Outputs: Some generic animal sound } }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.