Polymorphism
Introduction to Polymorphism
Welcome back! We're continuing our journey into object-oriented programming (OOP) with a new and exciting topic: Polymorphism. You've already learned about classes, objects, and inheritance, which are essential building blocks of OOP. Now, it's time to explore how polymorphism can make your code more flexible and reusable.
Polymorphism in Java
Polymorphism allows objects to be treated as instances of their parent class rather than their actual class. This provides a way to use a single interface to represent different types of objects. Here’s what we’ll cover in this lesson:
- Understanding Polymorphism: We'll discuss what polymorphism is and why it's a powerful concept in Java programming.
- Runtime Polymorphism: You'll learn how to use interfaces and method overriding to achieve runtime polymorphism.
- Compile Time Polymorphism: You'll understand method overloading and how it's used for compile-time polymorphism.
Understanding Polymorphism
Polymorphism in Java allows you to call derived class methods through a base class or interface reference. This can make your code more dynamic and general. Polymorphism in Java can be achieved through 2 distinct methods:
- Method Overriding (Runtime Polymorphism): This is when a subclass provides a specific implementation of a method that is already defined in its superclass. The method in the superclass is overridden by the method in the subclass.
- Method Overloading (Compile-Time Polymorphism): This is when multiple methods in the same class have the same name but different parameters. They may have different return types, but using different parameter lists allows Java to distinguish between them.
Polymorphism allows a single action to be performed in different ways. The ability to redefine methods in derived classes and have a unified method call mechanism via base classes or interfaces is a strength of Java OOP.
Runtime Polymorphism
Runtime polymorphism is achieved through method overriding. Here are the rules for method overriding:
- Same Method Signature: The method in the derived class must have the same name, return type, and parameters as the method in the base class.
- Inheritance: The class must be a subclass of the base class where the original method is defined.
- Access Modifier: The overriding method cannot have a more restrictive access modifier than the method in the base class. For example, if the base class method is
public, the overriding method cannot beprotectedorprivate. - Invocation: JVM determines which method to invoke at runtime based on the object's actual class, not the reference type.
- Annotations: It's a good practice to use the
@Overrideannotation to ensure that you are indeed overriding a method.
Example:
In this example, the sound method in Dog and Cat overrides the sound method in Animal. When sound is called on the Animal reference pointing to a Dog or Cat object, the respective sound method of Dog or Cat is invoked.
