1
Answer

C# constructor and methods

Febe

Febe

10y
798
1
Consider this example code illustrating how to use the constructor and methods of the class WorkRecord that stores a name and a number of hours worked: 


WorkRecord wA = new WorkRecord("Andy");  // hours == 0
WorkRecord wG = new WorkRecord("George"); // hours == 0
wG.AddHours(3); // update hours: 0+3=3
Console.WriteLine(wG.GetHours());  // prints  3
wG.AddHours(2); // update hours: 3+2=5
Console.WriteLine(wG);  // prints  George: 5 hours
Console.WriteLine(wA);  // prints  Andy: 0 hours

How do you complete the code for the constructor and the three methods in the class WorkRecord below?
 
public class WorkRecord
{
  private String name; // private instance variables for WorkRecord
  private int hours;
  /** Construct a WorkRecord for the specified name, with initial hours 0.
  public WorkRecord(string name)  // the constructor – code it!
  {
  }
  /** Return the number of hours in this WorkRecord. */
 public int GetHours()  // a getter method – code it!
 {
 }
  /** Update the number of hours when moreHours further hours are worked. */
 public void AddHours(int moreHours)  // an instance method – code it!
 {
  }
 /** Return a string in the form like the example:  Andy: 15 hours  */
  public override string ToString()  // the overridden ToString – code it!
 {
 }
}
Answers (1)