Class

 

class with a constructor

class Fruit {
String type;
// Constructor - Same name as class
Fruit(this.type);
}

void main() {
Fruit fruit = Fruit('apple');
print(fruit.type);
}

named parameters

class Fruit {
String type;
// Constructor - Same name as class
Fruit({this.type}); //new
}

void main() {
Fruit fruit = Fruit(type: 'Apple'); //new
print(fruit.type);
}

class that does not define a constructor

class BaristaNoConstructor {
String name;
int experience;
}

void main() {
  BaristaNoConstructor baristaNoConstructor = BaristaNoConstructor();
baristaNoConstructor.experience = 10;
print('baristaNoConstructor.experience: ${baristaNoConstructor.experience}');
// baristaNoConstructor.experience: 10
}

class that defines a constructor with named parameters

class BaristaWithConstructor {
String name;
int experience;
// Constructor - Named parameters by using { }
BaristaWithConstructor({this.name, this.experience});
// Method - return value
int whatIsTheExperience() {
return experience;
}
}

void main() {
// Class Named Constructor and return value
BaristaWithConstructor barista = BaristaWithConstructor(name: 'Sandy', experience: 10);
int experienceByProperty = barista.experience;
int experienceByFunction = barista.whatIsTheExperience();
print('experienceByProperty: $experienceByProperty');
print('experienceByFunction: $experienceByFunction');
// experienceByProperty: 10
// experienceByFunction: 10
}

defines a named constructor

class BaristaNamedConstructor {
String name;
int experience;
// Constructor - Named parameters { }
BaristaNamedConstructor({this.name, this.experience});
// Named constructor - baristaDetails - With named parameters
BaristaNamedConstructor.baristaDetails({this.name, this.experience});
}

void main() {
BaristaNamedConstructor barista = BaristaNamedConstructor.baristaDetails(name:
'Sandy', experience: 10);
print('barista.name: ${barista.name} - barista.experience: ${barista.experience}');
// barista.name: Sandy - barista.experience: 10
}

Class Inheritance

class BaristaNamedConstructor {
String name;
int experience;
// Constructor - Named parameters { }
BaristaNamedConstructor({this.name, this.experience});
// Named constructor - baristaDetails - With named parameters
BaristaNamedConstructor.baristaDetails({this.name, this.experience});
}

// Class inheritance
class BaristaInheritance extends BaristaNamedConstructor {
int yearsOnTheJob;
BaristaInheritance({this.yearsOnTheJob}) : super();
}

void main() {
// Init Inherited Class
BaristaInheritance baristaInheritance = BaristaInheritance(yearsOnTheJob: 7);
// Assign Parent Class variable
baristaInheritance.name = 'Sandy';
print('baristaInheritance.yearsOnTheJob: ${baristaInheritance.yearsOnTheJob}');
print('baristaInheritance.name: ${baristaInheritance.name}');
}





Comments