I'm still learning C# and just had a basic question about inheritance.
Lets 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 on the subclass which is passed no arguments or am I right in thinking that in order to create a default constructor on a subclass, the super class must have a default constructor too?
Also, if I were to add a default constructor to the super class, how would I initialize the super class variables in the subclass constructor? In java its super()
, in C# it's??
public SoccerPlayer():base()
{
base.name = "";
}
???
Constructor Chaining and the Default Constructor. Java guarantees that the constructor method of a class is called whenever an instance of that class is created. It also guarantees that the constructor is called whenever an instance of any subclass is created.
Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.
Unfortunately, subclasses don't inherit the constructor from the superclass, so they need their own, either explicitly created or a default constructor created by Java. In order to use a superclass, the subclass constructor must call the parent constructor.
A subclass can call a constructor defined by its superclass by use of the following form of super: super(parameter-list); Here, parameter-list specifies any parameters needed by the constructor in the superclass. super( ) must always be the first statement executed inside a subclass constructor.
You can create a parameterless constructor on the derived class, but it still needs to pass arguments to the base class constructor:
//Default constructor
public SoccerPlayer()
: base("default name", 0, default(Sexs))
{
}
Or you could add a default constructor to the base class...
you can have a parameter less constructor in child class but you need to invoke the parameterized constructor of base or same class like so
public Child():base(1,2,3)
{
}
or
public Child(): this(1,2,3)
{
}
In your case it wouldn't make much sense though. A soccer player can't have a default name or age.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With