Is it possible to define a member in a child class without defining it in an abstract parent class? FROM#

Just to clarify, is it really necessary that all members of the child class are declared above the abstract class above it?

Something like this would be possible:

public abstract class MyParent { public int x { get; set; } } public class MyChild : MyParent { public int x { get; set; } public string MyName { get; private set; } } 

This is just an example ... In this case, the MyName property MyName not defined in the parent class, but it is in the child class ... Is this possible?

Thanks in advance!

+6
inheritance c # abstract-class
source share
3 answers

Yes, you can declare additional properties and methods in a child class.

However, if you use a variable declared as an ancestor type, you can access members defined in the ancestor type through this variable. The only way to get a special class for a child class is to cast to a type with type child.

Aside: the child class should not duplicate declarations made in the ancestor. The int x property here will cause problems because there will be two different x properties around.

A specific (non-abstract) child class must override any virtual methods or properties declared by an abstract ancestor. Virtual and overriding ads require specific keywords.

+4
source share

Yes, it is possible to create new members in a child class that are not members of the parent class. The thing is to have child classes. The parent class must β€œextend” the parent class by adding new members or changing the behavior of existing members.

However, you do not need to recreate the parent members of the class in the child classes. Parent classes automatically receive all members of the parent class.

The code you provided is a legitimate C # program, and that means that you intend to create another int x for the child class. This is often not the case, and the Microsoft C # compiler will give you a warning about this.

+2
source share

Yes, of course, this is very normal for you. The only thing you cannot do is access the MyName property if you pass through the parent. In this case, you will only have access to the shared ones for MyParent.

+2
source share

All Articles