Skip to main content

Method Overloading and Overriding in Dart

Method Overloading and Overriding in Dart

Method Overloading and Method Overriding in Dart

Dart is a versatile, object-oriented programming language that supports method overriding but does not have direct support for method overloading. This blog explains these concepts in detail and provides practical examples to demonstrate their use.

Method Overriding

Method overriding allows a subclass to provide a specific implementation of a method defined in its parent class. This is an essential feature of polymorphism in Dart.

Key Features of Method Overriding:

  • The overridden method must have the same name, return type, and parameters as the parent method.
  • Use the @override annotation for clarity and to avoid errors.

Example:

class Animal {
  void sound() {
    print("Animal makes a sound");
  }
}

class Dog extends Animal {
  @override
  void sound() {
    print("Dog barks");
  }
}

void main() {
  Animal animal = Animal();
  animal.sound(); // Output: Animal makes a sound

  Animal dog = Dog();
  dog.sound(); // Output: Dog barks
}

Method Overloading

Dart does not natively support method overloading, where multiple methods have the same name but different parameter lists. Instead, you can achieve similar behavior using optional parameters or different method names.

Using Optional Parameters

Optional parameters in Dart allow you to define methods that can accept varying numbers of arguments.

Positional Optional Parameters:

class Calculator {
  void add(int a, [int? b]) {
    if (b != null) {
      print("Sum: \${a + b}");
    } else {
      print("Single value: \$a");
    }
  }
}

void main() {
  Calculator calc = Calculator();
  calc.add(5);       // Output: Single value: 5
  calc.add(5, 10);   // Output: Sum: 15
}

Named Optional Parameters:

class Calculator {
  void add({required int a, int b = 0}) {
    print("Sum: \${a + b}");
  }
}

void main() {
  Calculator calc = Calculator();
  calc.add(a: 5);          // Output: Sum: 5
  calc.add(a: 5, b: 10);   // Output: Sum: 15
}

Using Different Method Names

Instead of overloading, define methods with unique names for specific tasks.

class Printer {
  void printString(String text) {
    print("String: \$text");
  }

  void printNumber(int number) {
    print("Number: \$number");
  }
}

void main() {
  Printer printer = Printer();
  printer.printString("Hello");
  printer.printNumber(123);
}

Combining Overriding and Optional Parameters

Optional parameters can also be used in overridden methods to extend or modify their behavior.

Example:

class Shape {
  void draw({String color = "black"}) {
    print("Drawing a shape with color: \$color");
  }
}

class Circle extends Shape {
  @override
  void draw({String color = "red"}) {
    print("Drawing a circle with color: \$color");
  }
}

void main() {
  Shape shape = Shape();
  shape.draw(); // Output: Drawing a shape with color: black

  Shape circle = Circle();
  circle.draw(); // Output: Drawing a circle with color: red
}

Conclusion

While Dart does not directly support method overloading, its flexible optional parameters and method overriding features provide powerful alternatives. Understanding these concepts enables developers to write cleaner, more efficient code.

Want to learn more? Check out the Dart Documentation.

Comments

Popular posts from this blog

API Integration in Flutter - A Step-by-Step Guide

API Integration in Flutter - A Step-by-Step Guide API Integration in Flutter - A Step-by-Step Guide Learn how to integrate APIs into your Flutter app with this easy-to-follow tutorial. Step 1: Add Dependencies Start by adding the necessary dependencies for HTTP requests and JSON handling in your pubspec.yaml file. dependencies: flutter: sdk: flutter http: ^0.13.3 Run flutter pub get to install the dependencies. Step 2: Create a Service Class for API Calls Next, create a Dart file (e.g., api_service.dart ) to handle your API logic. Below is an example of a simple GET request function: import 'dart:convert'; import 'package:http/http.dart' as http; class ApiService { final String baseUrl; ApiService({required this.baseUrl...

Flutter Interview Preparation Topics

Flutter Interview Preparation Flutter Interview Preparation 1. Core Flutter Concepts **Widgets**: - StatelessWidget vs. StatefulWidget. - InheritedWidget and InheritedModel. - Custom Widgets (Creating reusable components). **State Management**: - Provider, Riverpod, Bloc/Cubit, Redux, or GetX. - Compare and contrast state management approaches. - Handling global and local state. **Navigation and Routing**: - `Navigator 1.0` vs. `Navigator 2.0`. - Named routes and deep linking. - Implementing nested navigation. **Lifecycle**: - App lifecycle (`AppLifecycleState`). - Widget lifecycle (`initState`, `dispose`, etc.). 2. Advanced Flutter Development **Performance Optimization**: - Efficient...

How, Purpose, and When to Use Google ML Kit in Flutter

How, Purpose, and When to Use Google ML Kit in Flutter How, Purpose, and When to Use Google ML Kit in Flutter Purpose of Google ML Kit in Flutter Google ML Kit simplifies adding AI features to mobile applications. Its primary purposes include: On-Device Machine Learning: Perform AI tasks without requiring an internet connection, ensuring low latency, privacy, and faster processing. Pre-trained Models: Use Google's robust, pre-trained models without needing ML expertise. Versatile AI Features: Enable functionalities like: Text recognition Barcode scanning Image labeling Face detection Pose detection Language identification Translation Entity extraction Smart replies When to Use Google ML Kit You should use Google ML Kit when: You need pre-built AI features withou...