Constructors and Inheritance

后端 未结 10 1080
臣服心动
臣服心动 2020-12-16 15:18

Lets take an example in C#

public class Foo
{
    public Foo() { }
    public Foo(int j) { }
}

public class Bar : Foo
{

}

Now, All the pu

10条回答
  •  不知归路
    2020-12-16 15:51

    The Foo constructor can only know how to initialize a Foo object, so it makes no sense that it should also know how to initialize any potential subclass

    public class Bar : Foo
    {
    public Bar(int i) : base(i) { }
    }
    

    The story the constructor tells is: "Hey base class please do whatever work you need to do to be in a good state so that I can go ahead and set up myself properly".

提交回复
热议问题