Ava Polymorphism
Ava Polymorphism
Method Overloading:
Occurs when multiple methods in the same class have the same name but different
parameters (different type, number, or both).
The method to be called is determined at compile-time based on the method signature.
class OverloadExample {
void display(int a) {
void display(String a) {
obj.display(10);
obj.display(10, 20);
obj.display("Hello");
Characteristics:
Method Overriding:
Occurs when a subclass provides a specific implementation for a method that is already defined
in its superclass.
The method call is determined at runtime based on the object's type.
class Animal {
void sound() {
@Override
void sound() {
System.out.println("Dog barks");
}
}
@Override
void sound() {
System.out.println("Cat meows");
Characteristics:
Methods must have the same name, return type, and parameters.
Allows a class to inherit the properties of another class and modify them to fit its needs.
Promotes the use of interfaces and abstract classes.
Important Points:
The @Override annotation is used to inform the compiler that the method is intended to
override a method in the superclass.
Method overriding allows the child class to provide a specific implementation of a
method that is already defined in its parent class.
Polymorphism in Java is achieved through inheritance and interfaces.
Advantages of Polymorphism
1. Flexibility: Allows methods to use objects of different types as if they were objects of the same
type.
2. Maintainability: Reduces code complexity by allowing the same interface to be used for
different underlying forms.
3. Extensibility: New classes can be introduced with minimal changes to existing code.
4. Reusability: Common code can be reused across different classes.
Disadvantages of Polymorphism
1. Performance Cost: May introduce a slight overhead due to the dynamic method resolution at
runtime.
2. Complexity: Can make code harder to understand and maintain if overused or misused.
Conclusion