Reputation: 3386
So I have a type called FunBond
, with a default constructor like this
public FunBond(int id,
string name,
Currency currency,
double notional,
DateTime maturityDate,
List<CashFlowWithDate> couponCashFlows,
DayCounter dayCounter)
: base(id, name, notional, InstrumentType.FixedRateBond, currency, maturityDate, dayCounter)
{
...
}
And DayCounter
is an abstract class
public abstract class DayCounter
{
public abstract string Name();
public abstract double YearFraction(DateTime d1, DateTime d2);
public abstract int DayCount(DateTime d1, DateTime d2);
}
Now my question is, what am I supposed to supply as a DayCounter
to generate an instance of a FunBond
? I can specify the id, name, currency, ... etc. etc. to pass as parameters to FunBond
, but what is DayCounter
supposed to be? I can't create an instance of it, and I can't supply it with anything I don't think... I thought I would need another class deriving from my abstract class to provide to FunBond
, so I think I misunderstand something fundamentally.
Upvotes: 7
Views: 12981
Reputation:
The question says:
I thought I would need another class deriving from my abstract class to provide to FunBond
That is correct - you need to create a concrete class from the abstract.
// Your derived class
public class WeekdayCounter : DayCounter
{
public override string Name() { return "Weekday" }
public override double YearFraction(DateTime d1, DateTime d2) { return 0.0; }
public override int DayCount(DateTime d1, DateTime d2) { return 0; }
}
// Create a FunBond
WeekdayCounter c = new WeekdayCounter(); // **derived class**
FunBond yay = new FunBond(id,
name,
currency,
notional,
maturityDate,
couponCashFlows,
c); // **WeekdayCounter, which is a DayCounter**
Upvotes: 0
Reputation: 27871
The constructor is declaring that it requires an parameter of type DayCounter
. Since DayCounter
is an abstract class then you need to pass an instance of a class that derives from DayCounter
.
That does not mean that you need to change the constructor parameter type, just pass an instance of a derived type.
The reason that someone defines a parameter of an abstract type is to allow polymorphism and loose coupling. You can have different derived classes of DayCounter
, each behaving differently (as long as they adhere to the contract of DayCounter
). And FunBond
can speak to instances of such classes without knowing how they internally work. As far as FunBond
is concerned, it is speaking to an object that adheres to the contract of DayCounter
, but doesn't care how it internally implemented.
Upvotes: 8