Method Overriding and Overloading

Method overriding and method overloading are two important concepts in object-oriented programming, particularly in languages like Java and C++.


Method Overriding

Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. The method in the subclass has the same name, return type, and parameters as the method in the superclass. By overriding a method, the subclass can provide its own implementation of the method, which may differ from the implementation in the superclass.


Key points about method overriding:

1. Same Signature: The overriding method must have the same name, return type, and parameter list as the method in the superclass.

2. Inheritance: Overriding occurs in a subclass inheriting from a superclass.

3. Runtime Polymorphism: When you call an overridden method on an object, the JVM determines which version of the method to execute based on the type of the object, not the reference type.


Example in Java:

class Animal {
    void makeSound() {
        System.out.println("Some generic sound");
    }
}

class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("Bark");
    }
}


Method Overloading

Method overloading occurs when a class has multiple methods with the same name but different parameter lists. The methods can differ in the number or type of parameters. Overloaded methods enable you to use the same method name for different behaviors.


Key points about method overloading:

1. Same Name: Overloaded methods have the same name but different parameter lists.

2. In the Same Class: Overloading occurs within the same class.

3. Compile-time Polymorphism: The decision on which overloaded method to call is made at compile time based on the method signature.


Example in Java:

class Calculator {
    int add(int a, int b) {
        return a + b;
    }
    
    double add(double a, double b) {
        return a + b;
    }
}


In this example, there are two `add` methods with different parameter types (int and double), making them overloaded methods.

In summary, method overriding is about providing a new implementation for a method in a subclass, while method overloading is about providing multiple methods with the same name but different parameters within the same class. Both concepts contribute to the flexibility and readability of object-oriented code.

Nenhum comentário:

Postar um comentário

Internet of Things (IoT) and Embedded Systems

The  Internet of Things (IoT)  and  Embedded Systems  are interconnected technologies that play a pivotal role in modern digital innovation....