Polymorphism basics

Polymorphism is a concept in Java that allows objects of different classes to be treated as if they are objects of the same class. This means that you can use a single interface or base class to represent a group of related classes and manipulate them in a uniform way.

In Java, polymorphism is achieved through method overriding and method overloading. Method overriding is when a subclass provides its own implementation of a method that is already defined in its superclass. Method overloading is when a class has multiple methods with the same name but different parameters.

Here is the basic syntax for method overriding in Java:

class Superclass {
    public void method() {
        System.out.println("This is the superclass method");
    }
}

class Subclass extends Superclass {
    public void method() {
        System.out.println("This is the subclass method");
    }
}

In this syntax, the Subclass provides its own implementation of the method that is already defined in the Superclass. When you call the method on an object of the Subclass, its implementation will be executed instead of the implementation in the Superclass.

Here is the basic syntax for method overloading in Java:

class MyClass {
    public void method(int a) {
        System.out.println("This is the method with one parameter");
    }

    public void method(int a, int b) {
        System.out.println("This is the method with two parameters");
    }
}

In this syntax, the MyClass has two methods with the same name but different parameters. When you call the method with one parameter, the first implementation will be executed. When you call the method with two parameters, the second implementation will be executed.

Here is an example of polymorphism in Java:

class Animal {
    public void speak() {
        System.out.println("I am an animal");
    }
}

class Dog extends Animal {
    public void speak() {
        System.out.println("Woof!");
    }
}

class Cat extends Animal {
    public void speak() {
        System.out.println("Meow!");
    }
}

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

        myAnimal.speak();
        myDog.speak();
        myCat.speak();
    }
}

In this example, we have a base class Animal and two subclasses Dog and Cat. Each subclass provides its own implementation of the speak method. In the main method, we create three objects of different types (Animal, Dog, and Cat) and call the speak method on each of them. Even though the objects have different types, they all inherit from the Animal class and can be treated as if they are objects of the same class. This is an example of polymorphism in action.