Skip to content

Latest commit

 

History

History
42 lines (30 loc) · 1.11 KB

ex5-2.md

File metadata and controls

42 lines (30 loc) · 1.11 KB

5.2 Initializing a Class Using a Constructor

Example Code:

The DaysLeftInWeek class constructor initializes the currentDay property to the current day of the week. If today is Wednesday, then the value of currentDay will be 3. The howManyDaysLeft() method then returns the number of days left in the week, minus the current day of the week. In this case, there are 5 days left in the week (Sunday, Monday, Tuesday, Wednesday, and Thursday).

The print() statements then print the current day of the week and the number of days left in the week to the console.

If you run the code on a different day of the week, the output will be different.

const numDays = 7;

class DaysLeftInWeek {
  int currentDay = 0;

  DaysLeftInWeek(){
    currentDay = DateTime.now().weekday.toInt();
  }

  int howManyDaysLeft(){
    return numDays - currentDay;
  }
}

void main() {
  var currentDay = DaysLeftInWeek();

  print ('Today is day ${currentDay.currentDay}');
  print ('We have ${currentDay.howManyDaysLeft()} day(s) left in the week');
}

Example Output:

Today is day 6
We have 1 day(s) left in the week