Polymorphism In Java
Polymorphism in Java is a concept that allows objects of different classes to be treated as objects of a common class. It enables objects to behave differently based on their specific class type. There are two types of polymorphism in Java:
- compile-time polymorphism
- runtime polymorphism.
1.Compile-time polymorphism is achieved by method overloading, which means having multiple methods with the same name but different parameters. The compiler decides which method to call based on the number and types of arguments passed to the method. For example, you can have a class Helper that has two methods called Multiply, one that takes two int arguments and one that takes two double arguments. Depending on the arguments you pass to the Multiply method, the compiler will choose the appropriate method to execute.
2.Runtime polymorphism is achieved by method overriding, which means having a subclass that inherits a method from a superclass and provides a different implementation for it. The method to be called is determined by the JVM at runtime, based on the actual object type that the reference variable points to. For example, you can have a class Animal that has a method called eat, and a subclass Dog that inherits from Animal and overrides the eat method. If you have a reference variable of type Animal that points to an object of type Dog, then calling the eat method will invoke the overridden method in Dog class.