Question #50MediumFlutter Basics

Flutter OOPS concept must know (refer the question number 76)

#flutter#oops

Answer

Overview

This question refers to Question #5 (OOP Concepts). For a complete and detailed explanation of Object-Oriented Programming concepts in Flutter/Dart, including:

  • Encapsulation - Hiding internal state
  • Inheritance - Code reuse through parent-child relationships
  • Polymorphism - Same interface, different implementations
  • Abstraction - Showing only essential features

Please refer to Question 5 in this document.


Quick Summary

The four pillars of OOP that every Flutter developer must know:

1. Encapsulation

dart
class BankAccount {
  double _balance = 0; // Private field

  double get balance => _balance; // Controlled access

  void deposit(double amount) {
    if (amount > 0) _balance += amount;
  }
}

2. Inheritance

dart
class Animal {
  void speak() => print('Animal sound');
}

class Dog extends Animal {
  
  void speak() => print('Woof!');
}

3. Polymorphism

dart
abstract class Shape {
  double area();
}

class Circle extends Shape {
  final double radius;
  Circle(this.radius);

  
  double area() => 3.14159 * radius * radius;
}

class Rectangle extends Shape {
  final double width, height;
  Rectangle(this.width, this.height);

  
  double area() => width * height;
}

4. Abstraction

dart
abstract class PaymentGateway {
  Future<bool> processPayment(double amount);
  void showReceipt();
}

class RazorpayGateway extends PaymentGateway {
  
  Future<bool> processPayment(double amount) async {
    // Implementation details hidden
    return true;
  }

  
  void showReceipt() => print('Receipt');
}

Additional Important OOP Concepts

Interfaces (via implements)

dart
abstract class Flyable {
  void fly();
}

class Bird implements Flyable {
  
  void fly() => print('Bird flying');
}

Mixins

dart
mixin Logger {
  void log(String msg) => print('[LOG] $msg');
}

class UserService with Logger {
  void createUser() {
    log('Creating user');
  }
}

Reference

For the complete, in-depth explanation with extensive code examples, comparison tables, and best practices, see Question 5: OOP Concepts in this document.


Resources