1. Inheritance

Definition and Importance:

Inheritance is a core principle of object-oriented programming where a new class, called a subclass or derived class, can inherit properties and methods from an existing class, known as a superclass or base class.

Example Clarification:

Real-World Analogy:

An analogy to explain inheritance could be a “vehicle” superclass, with “car” and “truck” subclasses inheriting common features like wheels and engines but having their distinct properties and behaviors.

class Car {
  String name;
  
  Car(this.name);
  
  void drive() => print("Driving a Car");
}

The Car the class represents a basic car with a name property and a drive method.

class ElectricCar extends Car {
  double chargeCapacity;
  
  ElectricCar(String name, this.chargeCapacity) : super(name);
}


2. Method Overriding

Definition and Purpose:

Method overriding allows a subclass to provide a specific implementation of a method that is already defined in its superclass. This enables subclasses to tailor behavior to their specific needs while maintaining a common interface.

Example Explanation:

Use Cases:

Method overriding is commonly used in scenarios where a subclass needs to customize behavior inherited from its superclass, such as providing specialized functionality for different types of vehicles.

class ElectricCar extends Car {
  double chargeCapacity;
  
  ElectricCar(String name, this.chargeCapacity) : super(name);
  
  @override
  void drive() => print('Driving an electric car');
}


Putting It All Together

Practical Demonstration:

Real-World Relevance:

Understanding inheritance and method overriding is essential for designing modular, maintainable, and extensible software systems, particularly in complex applications where classes and hierarchies abound

// Inheritance
void main() {
  final electricVehicle = ElectricCar('TATA', 2900);
  electricVehicle.drive();
}

class Car {
  String name;
  
  Car(this.name);
  
  void drive() => print("Driving a Car");
}

class ElectricCar extends Car {
  double chargeCapacity;
  
  ElectricCar(String name, this.chargeCapacity) : super(name);
}

// Method Overriding
void main() {
  final electricVehicle = ElectricCar('TATA', 2900);
  print(electricVehicle.name);
  electricVehicle.drive();
}

class Car {
  String name;
  
  Car(this.name);
  
  void drive() => print("Driving a Car");
}

class ElectricCar extends Car {
  double chargeCapacity;
  
  ElectricCar(String name, this.chargeCapacity) : super(name);
  
  @override
  void drive() => print('Driving an electric car');
}

This demonstrates how inheritance and method overriding work in Dart, allowing for code reuse and the ability to specialize behavior in sub classes. Understanding these concepts is crucial for building maintainable and extensible object-oriented Dart applications.


🌟 Stay Connected! 🌟

Hey there, awesome reader! 👋 Want to stay updated with my latest insights,Follow me on social media!

🐦 📸 📘 💻 🌐

Sadanand Gadwal