New to OOP and I'm confused by how derived-class constructors work when inheriting from a base class in C#.
First the base class:
class BaseClass
{
private string BaseOutput = null;
public BaseClass(string BaseString)
{
BaseOutput = BaseString;
}
public virtual void PrintLine()
{
Console.WriteLine(BaseOutput);
}
}
Here is the derived class:
class SubClass : BaseClass
{
private string SubOutput = null;
public SubClass(string BaseString, string SubString) : base(BaseString)
{
SubOutput = SubString;
}
public override void PrintLine()
{
Console.WriteLine(SubOutput);
}
}
Finally, the main part of the program:
class Program
{
static void Main(string[] args)
{
BaseClass theBase = new BaseClass("Text for BaseClass");
SubClass theSub = new SubClass("2nd param", "Text for SubClass");
theBase.PrintLine();
theSub.PrintLine();
Console.ReadKey();
}
}
What I don't get is why, when calling the constructor for the derived class, I have to also pass the parameter that the base class needs. Shouldn't the BaseOutput field in the derived class just stay set to null if no value is assigned to it? Why can't something like this work:
public SubClass(string SubString) : base(BaseString)
Furthermore, when calling the constructor in this derived class, the first parameter has to be named the same as the one in the base class or else it throws an error. If I were to define a new string variable called AnotherString in the derived class, why wouldn't this work:
public SubClass(string AnotherString, string SubString) : base(BaseString)
Lastly, when you do this the right way and type out this...
public SubClass(string BaseString, string SubString) : base(BaseString)
...what is the first parameter in the SubClass constructor used for? It's not being assigned or used in any methods for my derived class. Why do I have to even put it there at all?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…