Skip to content

Instantly share code, notes, and snippets.

@abdorll
Created October 16, 2023 02:26
Show Gist options
  • Save abdorll/48a6207eff95ce2cb9b85f77e2c9865c to your computer and use it in GitHub Desktop.
Save abdorll/48a6207eff95ce2cb9b85f77e2c9865c to your computer and use it in GitHub Desktop.
class Book {
// Private Properties
String? _title;
String? _author;
double? _price;
// Getter to read the private property _title
String get title => this._title!;
// Setter to update the private property _title
set title(String title) => this._title = title;
// Getter to read the private property _author
String get author => this._author!;
// Setter to update the private property _author
set author(String author) => this._author = author;
// Getter to read the private property _price
double get price => this._price!;
// Setter to update the private property _price
set price(double price) {
if (price < 0) {
throw Exception("Price cannot be negative");
}
this._price = price;
}
}
void main() {
// Create an object of the Book class
Book myBook = Book();
// Set book properties using setters
myBook.title = "The Great Gatsby";
myBook.author = "F. Scott Fitzgerald";
myBook.price = 12.99;
// Access and display book details using getters
print("Title: ${myBook.title}");
print("Author: ${myBook.author}");
print("Price: \$${myBook.price.toStringAsFixed(2)}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment