Just to clarify, is it really mandatory that all the members of a child class are declared on the abstract class above it?
Would be possible something like this:
public abstract class MyParent
{
public int x { get; set; }
}
public class MyChild : MyParent
{
public int x { get; set; }
public string MyName { get; private set; }
}
It's just an example... In such case, the property MyName
is not defined in the parent class, but it is in the child class... Is it possible?
Thanks in advance!
Yes, you can declare additional properties and methods in the child class.
However, if you are using a variable that is declared to be the ancestor type, you will only be able to access the members defined in the ancestor type through that variable. The only way to get to the child class's special stuff is to typecast down to the child type.
As an aside: the child class should not duplicate the declarations made in the ancestor. Your int x property here will cause problems because there will be two different x properties running around.
A concrete (non-abstract) child class is required to override any virtual methods or properties declared in the abstract ancestor. Virtual and override both require specific keywords in the declaration.
yes of course it's very normal for you to do this. The only thing you can't do though is access the MyName property if you are going through the parent. In that case you would just have acces to those common to MyParent.
Yes it is possible to create new members in a child class that are not in the parent class. That's the whole point of having child classes. Child class is supposed to "extend" a parent class by adding new members or modifying the behavior of existing members
However, You need not recreate parent class members in the child classes. Child classes get all the members from the parent class automatically.
The code you have given is a legal C# program and it means that your intention is to create a different int x for the child class. This is often not the case and Microsoft C# compiler will give you a warning about it.
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