Singleton class And Setter, Getter
// This is the main () function
void main() {
// This constructor calls the factory constructor,
// which turns around and returns the static instance
// which was initialized with the `_internal` named constructor
//This will be true if the two instances have the same hashcode
// (hint: they do)
print(Student().hashCode == Student().hashCode);
//*****************************************
// Create an object of Student class
Student st = Student();
// setting values to the object using a setter
st.firstName = "Surya Prakash";
st.lastName = "Yadav";
st.age = 28;
// Display the values of the object
print("Full Name: ${st.fullName}");
print("Age: ${st.age}");
}
// Create Student Class
//****************************************************************************
class Student {
//Create singleton constructor
Student._primaryConstructor();
static final Student _instance=Student._primaryConstructor();
// Create Factory Method
factory Student(){
return _instance;
}
// Private Properties
String? _firstName;
String? _lastName;
int? _age;
// Getter to get full name
String get fullName => this._firstName! + " " + this._lastName!;
// Getter to read private property _age
int get age => this._age!;
// Setter to update private property _firstName
set firstName(String firstName) => this._firstName = firstName;
// Setter to update private property _lastName
set lastName(String lastName) => this._lastName = lastName;
// Setter to update private property _age
set age(int age) {
if (age < 0) {
throw Exception("Age can't be less than 0");
}
this._age = age;
}
}
Comments
Post a Comment