How do you use polymorphism with a simple code example?

Polymorphism is a core concept in object-oriented programming that allows methods to do different things based on the object it is acting upon. It enables a single interface to represent different underlying forms (data types). In Java, polymorphism can be achieved through method overriding and method overloading.

Here's a simple example demonstrating how polymorphism works using method overriding:

class Animal {
            void sound() {
                System.out.println("Animal makes a sound");
            }
        }

        class Dog extends Animal {
            void sound() {
                System.out.println("Dog barks");
            }
        }

        class Cat extends Animal {
            void sound() {
                System.out.println("Cat meows");
            }
        }

        public class Main {
            public static void main(String[] args) {
                Animal myDog = new Dog();
                Animal myCat = new Cat();

                myDog.sound(); // Output: Dog barks
                myCat.sound(); // Output: Cat meows
            }
        }
        

Java Polymorphism Object-Oriented Programming Method Overriding Method Overloading