Object-Oriented Programming

This example demonstrates a simple inventory management system.

class Product {
  String name;
  double price;
  int quantity;

  Product(this.name, this.price, this.quantity);

  double get totalValue => price * quantity;

  void restock(int amount) {
    quantity += amount;
    print('$amount units added to $name. New quantity: $quantity');
  }

  @override
  String toString() {
    return '$name: \$${price.toStringAsFixed(2)} (Quantity: $quantity)';
  }
}

class Inventory {
  List<Product> products = [];

  void addProduct(Product product) {
    products.add(product);
    print('Added: $product');
  }

  void displayInventory() {
    for (var product in products) {
      print(product);
    }
  }

  double get totalInventoryValue {
    return products.fold(0, (total, product) => total + product.totalValue);
  }
}

void main() {
  var inventory = Inventory();

  var apple = Product('Apple', 0.5, 100);
  var banana = Product('Banana', 0.3, 150);
  var orange = Product('Orange', 0.8, 200);

  inventory.addProduct(apple);
  inventory.addProduct(banana);
  inventory.addProduct(orange);

  inventory.displayInventory();
  print('Total Inventory Value: \$${inventory.totalInventoryValue.toStringAsFixed(2)}');

  apple.restock(50);
  inventory.displayInventory();
}

Comments

Leave a Reply

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