example of polymorphisim in java
Polymorphism in Java is achieved through method overriding. Here is an example of polymorphism in Java using method overriding:
```java
class Animal {
public void makeSound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Bark");
}
}
class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow");
}
}
public class Main {
public static void main(String[] args) {
Animal dog = new Dog();
Animal cat = new Cat();
dog.makeSound(); // Output: Bark
cat.makeSound(); // Output: Meow
}
}
```
In the above example, we have a superclass `Animal` with a method `makeSound()`. The `Dog` and `Cat` subclasses override the `makeSound()` method with their own implementations. When we create objects of `Dog` and `Cat` classes and call the `makeSound()` method, Java uses dynamic method dispatch to determine which implementation of the method to call. This is an example of polymorphism in Java.