Reputation: 184
I have this coding exercise where a base class constructor should be able to define a custom property value using input parameters, but the derived class should set this property to a fixed value.
A snippet of the exercise text:
Manager
… a manager also has a monthly bonus, which should be specified at construction…”Director
. The Director
class is supposed to be derived from the Manager
class. A director is just a manager who has a fixed monthly bonus of 20000… When implementing the Director
class, pay special attention to implementing the constructor correctly. Does the class need anything else than a constructor? “So how can I set this fixed value in the derived class by only having a constructor in this class? Also: the creator of the subclass object should not be able to set this property (monthlyBonus
) at all.
//Manager inherits Employee (not interesting in this context)
public Manager(string name, int salaryPerMonth, int monthlyHours, int monthlyBonus) : base(name, salaryPerMonth)
{
MonthlyHours = monthlyHours;
Bonus = monthlyBonus;
}
public class Director : Manager
{
public Director(string name, int salaryPerMonth, int monthlyHours, int monthlyBonus = 20000) : base(name, salaryPerMonth, monthlyHours, monthlyBonus)
{
//base.Bonus = 20000;
}
}
I thought about removing the input parameter monthlyBonus
in the Director
class in make a variable inside the constructor, but since the base class constructor gets called first thats not going to work i guess.
I also thought about setting the input parameter value as an optional value but then the caller would be able to change this value, so this is not accepted either.
Upvotes: 1
Views: 2127
Reputation: 70671
The short answer is that you just need to change the constructor declaration:
public Director(string name, int salaryPerMonth, int monthlyHours)
: base(name, salaryPerMonth, monthlyHours, 20000) { }
I.e. omit (as you already did) the monthlyBonus
parameter, and hard-code the value when you call the base constructor using base
.
Since this is clearly a classwork exercise, I would encourage you to ask questions focused on why it is you weren't already aware that you could do this, so that you can understand better how the base()
constructor invocation works.
For now, I'll just point out that it's essentially the same as any other method invocation, and you can do everything with it that you can in any other method invocation. The parameters can be any expression you want; they don't need to just be a repetition of the parameters in the derived constructor.
Upvotes: 1
Reputation: 49779
you can directly pass values in base constructor
public class Director : Manager
{
public Director(string name, int salaryPerMonth, int monthlyHours,)
:base(name, salaryPerMonth, monthlyHours, 20000)
{
}
}
Upvotes: 1