Google News
logo
Dart - Interview Questions
What Is Method Overriding In Dart?
Method overriding in Dart is a feature of object-oriented programming that allows a subclass to provide a different implementation for a method that is already defined in its superclass. When a method in the subclass has the same name, return type, and parameters as a method in the superclass, it overrides the superclass method.

Here are the key points to understand method overriding in Dart:

1. Inheritance Relationship : Method overriding occurs in the context of inheritance, where one class (subclass) inherits properties and behaviors from another class (superclass).

2. Same Signature : For a method in a subclass to override a method in its superclass, they must have the same name, return type, and parameter types. The method in the superclass must also be marked with the `@override` annotation to explicitly indicate the intention to override.
   class Superclass {
     void someMethod() {
       print('Superclass method');
     }
   }

   class Subclass extends Superclass {
     @override
     void someMethod() {
       print('Subclass method');
     }
   }​

   In this example, the `Subclass` overrides the `someMethod()` from the `Superclass` by providing its own implementation.
3. Invocation : When a method is invoked on an object of the subclass, the Dart runtime first checks if the method is overridden in the subclass. If it is, the overridden method in the subclass is executed. If not, the method in the superclass is executed.
   Superclass superObj = Superclass();
   Subclass subObj = Subclass();

   superObj.someMethod();  // Output: Superclass method
   subObj.someMethod();    // Output: Subclass method​

   Here, the `someMethod()` is invoked on both `superObj` and `subObj`. The actual implementation executed depends on the type of the object.

Method overriding allows subclasses to provide specialized behavior while still maintaining the inheritance hierarchy. It enables polymorphism, where objects of different classes can be used interchangeably, and the appropriate method implementation is called based on the actual object type at runtime. This feature is fundamental to achieving code reusability, extensibility, and supporting dynamic dispatch in Dart's object-oriented programming paradigm.
Advertisement