Question

This is probably a simple thing to fix. I'm a university student and we just started polymorphism, so the concept is still puzzling to me.

abstract class IncreaseTransaction
{
    private string _Description;
    private decimal _Amount;        

    protected IncreaseTransaction(string description, decimal amount)
    {
        _Description = description;
        _Amount = amount;
    }
}

class Deposit : IncreaseTransaction
{
    public Deposit(string description, decimal amount) : base("Deposit", amount)
    {
    }
}

static void Main(string[] args)
{
    Customer fred = new Customer("Fred");
    SavingsAccount fredSavings = new SavingsAccount();
    fredSavings.AddTransaction(new Deposit(500.00M));
}

When a new deposit is instantiated, I want the literal string "Deposit" to be used as the description for the transaction. However, I'm getting an error stating 'SampleNamespace.Deposit does not contain a constructor that takes one argument'. So, the string is not being inherited, and I am unsure how to fix this. I would greatly appreciate any help!

Était-ce utile?

La solution

Your constructor for Deposit takes two parameters:

public Deposit(string description, decimal amount) : base("Deposit", amount)

Since you're setting "Deposit" in the call to base(), you don't need 'string description' in that constructor. It should look like:

public Deposit(decimal amount) : base("Deposit", amount)

The following line should no longer throw an error:

fredSavings.AddTransaction(new Deposit(500.00M));

Additional Explanation: Constructors are not inherited like members or properties, but are unique to both the child and parent. The child (Deposit) has to invoke the base class's (IncreaseTransaction) constructor, but it does not need to require the same parameters in its own constructor.

Here is an old (but good) discussion of why this is the case: Why are constructors not inherited?

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top