Reputation: 8695
I'm working through an example in the bookPro C# and the .NET Platform
and I'm making a mistake somewhere that I can't see. The program compiles and runs, but the Manager
object in this example isn't having the right value of 'StockOptions' returned. In an effort of concision, I'm going to try to only post the relevant code because this example is all about class hierarchies and there's like six different classes. The virtual method GiveBonus
in the Employee
class isn't being correctly overridden in the Manager
class.
class Manager : Employee
{
private int numberOfOpts;
//the properties are inherited from Employee
public int StockOptions { get; set; }
//***METHODS*** this is returns the StockOptions amount as it is in the
// constructor, there's no logic being applied
public override void GiveBonus(float amount)
{
base.GiveBonus(amount);
Random r = new Random();
numberOfOpts += r.Next(500);
}
public override void DisplayStats()
{
base.DisplayStats();
Console.WriteLine("you have {0} stock options", StockOptions);
}
public Manager() { }
public Manager(string fullName, int age, int empID, float currPay,
string ssn, int numbofOpts) : base(fullName, age, empID, currPay, ssn)
{
ID = empID;
Age = age;
Name = fullName;
Pay = currPay;
StockOptions = numbofOpts;
}
}
snippet from my Main() method
Manager chucky = new Manager("chucky", 50, 92, 100000, "333-33-3333", 9000);
chucky.GiveBonus(300);
chucky.DisplayStats();
Console.WriteLine();
I made a mistake while asking the question. What I should have asked is why I have to use
Console.WriteLine("you have {0} stock options", numbOfOpts);
instead of
Console.WriteLine("you have {0} stock options", StockOptions);
Upvotes: 1
Views: 236
Reputation: 1499800
It's not meant to add a random number to 9000 - it's meant to give a random number of stock options as well as the "base" pay bonus:
public override void GiveBonus(float amount)
{
base.GiveBonus(amount);
Random r = new Random();
// Note numberOfOpts, not currPay
numberOfOpts += r.Next(500);
}
Unfortunately, as we've got two separate fields - one created by an automatically implemented property - it won't actually update the value of StockOptions
... it's not clear whether this is due to your editing, or whether it's a mistake in the book. (There are various other things I dislike about this code, but hey...)
Upvotes: 4