metadeck
10/5/2018 - 10:19 AM

Beginners Dart - Class Constructors

Beginners Dart - Class Constructors

class ClassAnimal {

  //So this variable is now global class variable that is private to this class.
  String _name = "";

  /*

  Animal() { //Here I created a function that would automatically name the private variable to bill, however this lacks functionality, and what is we want to name the animal from our main code?

    print("Constructed"); //Print the word Constructed.
    _name = "Bill"; //Add a value of "Bill" to the private variable.

  }

  */

  //Here we are asking for a parameter to be passed.
  ClassAnimal(String name) {

    //So now we have a default constructor that requires a parameter to be passed when the name variable is used.
    _name = name;

  }

  void sayHello() {

    if(_name.isEmpty) {

      print("Hello");

    }else {

      print("Hello ${_name} nice to meet you.");

    }

  }

}

//Remember to use this class we need to add it to the pubspec file and import it to our main code.

void main() {
 
  
  //Here we created two new instances of the class, one for cat and one for dog, because we have a defaut constructor that requires a parameter, these functions need a string value passed, otherwise the code will break.
  ClassAnimal cat = new ClassAnimal("Bob");
  ClassAnimal dog = new ClassAnimal("Frank");

  //Now we call each class instance individually, printing the full sentence and names to the screen.
  cat.sayHello();
  dog.sayHello();
  
}