Understanding Abstract Classes in Dart: Benefits, Memory Usage, and Flexibility | Full concept about abstract class

Important point :

Abstract classes are not “empty”:

  • They can have methods (with or without implementation) and variables.
  • However, they cannot be instantiated directly.

Acts as a base class:

  • Abstract classes are mainly used as blueprints for other classes.
  • They help enforce a structure for subclasses to follow by defining abstract methods that must be implemented in derived classes.

NEED OF ABSTRACT CLASS IN DART

✅ Avoiding Code Duplication ✅ Polymorphism (Flexible Code) ✅ Enforcing a Common Structure

✅ When multiple classes share common behavior.
✅ When you want to enforce a contract (certain methods must be implemented).
✅ When you want to avoid code duplication.
✅ When polymorphism is needed (using a parent type to refer to child classes).

Does an Abstract Class Use Memory?

They only provide a structure (like a blueprint) that other classes follow.

Only the subclass exists in memory, not the abstract class

Abstract class example:

abstract class Animal {
  void makeSound(); // Just a method signature, no memory used
}

class Dog extends Animal {
  String name; // Uses memory when Dog is created

  Dog(this.name);

  @override
  void makeSound() {
    print("$name says Bark!");
  }
}

void main() {
  Dog myDog = Dog("Buddy"); // Memory is allocated for 'myDog', not 'Animal'
  myDog.makeSound(); // Buddy says Bark!
}

Advantages:

No duplicate code → The Animal class enforces structure.
Scalability → Adding a new animal requires only a new class extending Animal.
Flexibility → We can store different animals in the same list (List<Animal>).
Better maintainability → If we want to change how animals behave, we update the Animal class instead of modifying each class separately.

Without Abstract class:

class Dog {
  void makeSound() {
    print("Bark! Bark!");
  }
}

class Cat {
  void makeSound() {
    print("Meow! Meow!");
  }
}

void main() {
  Dog dog = Dog();
  Cat cat = Cat();

  dog.makeSound(); // Output: Bark! Bark!
  cat.makeSound(); // Output: Meow! Meow!
}

Problems:

Duplicate method names (makeSound() in both Dog and Cat).
❌ No shared structure → If we add another animal, we must manually add makeSound().
No flexibility → We can’t create a list of animals and call makeSound() dynamically.

Conclusion:
If you don’t use an abstract class: Your code still works but may become messy, repetitive, and hard to maintain. Abstract classes don’t use extra memory, they just provide structure. For small projects, you may not need them, but for larger projects, they improve organization and reusability.

Leave a Reply

Your email address will not be published. Required fields are marked *

web_horizontal
About Us Disclaimer Privacy Policy Terms & Conditions Contact Us

Copyright © 2023 ResearchThinker.com. All rights reserved.