Polymorphism gives the meaning many forms, usually it occurs when multiple classes are present and have been inherited.
Consider an example of installing an application in your mobile, where your base class is Mobile and method is installation() and its derived classes could be installApp1, installApp2, installApp3 etc which will have its own implementation but installation method can be common which can be inherited from its base class.
Polymorphism is a fundamental concept in object-oriented programming that allows objects of different classes to be treated as if they were of the same class. In Java, polymorphism can be achieved in two ways: through method overloading and method overriding.
Method Overloading:
Method overloading is a technique in Java where multiple methods can have the same name but different parameters. The Java compiler determines which method to call based on the number and types of arguments passed to the method. For example:
public class Example {
public void print(int x) {
System.out.println("Printing integer: " + x);
}
public void print(String x) {
System.out.println("Printing string: " + x);
}
}
Example example = new Example();
example.print(10);
example.print("Hello World");
In the above example, the Example class has two methods with the same name print, but with different parameters (an integer and a string). Depending on the type of argument passed, the appropriate method will be called.
Method Overriding:
Method overriding is a technique in Java where a subclass provides a different implementation for a method that is already defined in its superclass. This allows objects of the subclass to be treated as objects of the superclass, and the correct implementation of the method is determined at runtime. For example:
public class Animal {
public void makeSound() {
System.out.println("Some sound");
}
}
public class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow");
}
}
Animal animal = new Cat();
animal.makeSound();
In the above example, the Cat class extends the Animal class and overrides its makeSound method. When an object of the Cat class is assigned to a variable of type Animal, the makeSound method of the Cat class is called at runtime. This allows objects of different classes to be treated as objects of the same class, as long as they share a common superclass or interface.
Polymorphism is an important concept in Java, as it allows for more flexible and extensible code that can be easily adapted to changing requirements.