Creating a default constructor in a subclass

I'm still learning C # and just asked the main question about inheritance.

Let's say I have an abstract class SportsPlayer:

public abstract class SportsPlayer
{

    string name;    /*1ai*/
    int age;        /*1aii*/
    Sexs gender;    /*1aiii*/ 

    //1b
    public SportsPlayer(string n, int a, Sexs g)
    {
        this.name = n;
        this.age = a;
        this.gender = g;
    }
}

And a subclass called SoccerPlayer:

public class SoccerPlayer : SportsPlayer
    {
        Positions position;
        public SoccerPlayer(string n, int a, Sexs g, Positions p)
            : base(n, a, g)
        {
            this.position = p;
        }

        //Default constructor
        public SoccerPlayer()
        {

        }

Is it possible to create a constructor in a subclass that did not pass any arguments, or am I right in thinking that in order to create a default constructor in a subclass, a superclass must have a default constructor?


Also, if I were to add a default constructor to the superclass, how would I initialize the superclass variables in the subclass constructor? In java it super(), in c # it?

public SoccerPlayer():base()
{
    base.name = "";
}

???

+5
source share
3 answers

, :

    //Default constructor
    public SoccerPlayer()
        : base("default name", 0, default(Sexs))
    {

    }

...

+6

, ,

public Child():base(1,2,3)
{
}

public Child(): this(1,2,3)
{
}

. .

+5

You can create your own new constructor, but if you do not call base(...), then you cannot initialize in the base class.
Therefore you should use:

public SoccerPlayer()
    :base("name", 30, Sexs.???)
{
}
+2
source

All Articles