Java Polymorphism
In Java, polymorphism is a concept that allows objects of different classes to be treated as if they were objects of the same class. This means that you can write code that works with objects of a certain type, and that same code will work with objects of any class that is a subclass of that type.
Polymorphism is achieved through inheritance and method overriding. When a class is defined as a subclass of another class, it inherits all of the methods and fields of the parent class. The subclass can then override the methods of the parent class with its own implementations.
For example, consider the following classes:
public class Animal { public void makeSound() { System.out.println("The animal makes a sound"); } } public class Cat extends Animal { public void makeSound() { System.out.println("Meow!"); } } public class Dog extends Animal { public void makeSound() { System.out.println("Woof!"); } }
In this example, the Animal class defines a method called "makeSound()", and the Cat and Dog classes both override this method with their own implementations. When a method that works with Animal objects is called, it can work with objects of the Cat or Dog classes as well, since they are both subclasses of Animal.
Here is an example of how polymorphism can be used in Java:
Animal animal1 = new Cat(); Animal animal2 = new Dog(); animal1.makeSound(); // Output: Meow! animal2.makeSound(); // Output: Woof!
In this example, the "animal1" variable is declared as an Animal, but is initialized as a Cat. The "animal2" variable is declared as an Animal, but is initialized as a Dog. When the "makeSound()" method is called on these objects, the method that is executed is the one that is defined in the subclass.
Polymorphism is a powerful feature of object-oriented programming that allows code to be more flexible and reusable. It is a key concept in Java programming, and is used extensively in the Java class library and in many Java applications.