1 Person class and constructors
-
Start a new project in Visual Studio and name it
Company. -
Create a
Modelsfolder. -
Create a class named
Personinside it.The class diagram for the
Personclass looks like this:Note that the attribute
NumberOfPeopleis static. This attribute is used in this assignment to keep track of how many people have been added (explained below). -
Add the following line to the class:
1public static int NumberOfPeople = 0;Remember that a static attribute exists in the class and is available outside instances. The static attribute
NumberOfPeopleis set to 0 when thePersonclass is loaded. -
Add the remaining attributes according to the class diagram.
-
Add the all-args constructor as follows:
1 2 3 4 5 6 7
public Person(string name, string city, double monthlySalary) { this.Name = name; this.City = city; this.MonthlySalary = monthlySalary; this.EmployeeNumber = ++NumberOfPeople; }The
EmployeeNumberattribute is assigned dynamically. First the static attributeNumberOfPeopleis incremented by 1 (the plus signs precede the attribute), and the new value is then assigned toEmployeeNumber. The next steps will demonstrate this. -
Create a new
Programclass in the project root (or use the existingProgram.cs). -
Add the following code to your
Mainmethod:1 2 3 4 5 6 7
Console.WriteLine(Person.NumberOfPeople); Person boss = new Person("Mark", "Den Haag", 10000); Console.WriteLine(Person.NumberOfPeople); Console.WriteLine(boss.EmployeeNumber); Person employee = new Person("Caroline", "Delft", 4000); Console.WriteLine(Person.NumberOfPeople); Console.WriteLine(employee.EmployeeNumber);- Initially
NumberOfPeopleis 0. - When instantiating
boss,NumberOfPeopleis incremented by 1 (and thus equals 1). - This value is assigned to the
EmployeeNumberattribute ofboss. - When instantiating
employee,NumberOfPeopleis incremented by 1 (and thus equals 2). - This value is assigned to the
EmployeeNumberattribute ofemployee.
- Initially
-
Run your program and check the output.
-
Create the second constructor
Person(string name).a) Use the default values "Unknown" for
cityand 0 formonthlySalary.
b) Assign theEmployeeNumberattribute as done above. -
Create the default constructor
Person().a) Use the default value "Unknown" for
nameand the default values forcityandmonthlySalaryas described above.
b) Assign theEmployeeNumberattribute as done above. -
Add the
CalculateYearlyIncomemethod.a) The yearly income is 12 times the monthly salary.
-
Add the following code to your
Mainmethod (below the existing code):1 2 3 4 5
Person assistant = new Person("Klaas"); Person manager = new Person(); Console.WriteLine(Person.NumberOfPeople); Console.WriteLine($"{boss.Name} earns {boss.CalculateYearlyIncome():C} per year"); Console.WriteLine($"{assistant.Name} lives in {assistant.City}"); -
Run your program. The output should look like:
1 2 3 4 5 6 7 8
0 1 1 2 2 4 Mark earns € 120.000,00 per year Klaas lives in Unknown