c# classe inherited code example
Example: c# inheritance
// ----------------- INHERITANCE and POLYMORPHISM ------------------ //
// ----- TOP CLASS ----- //
class Parent
{
protected int ID; // This will be inherited by the child class
public Parent() // This constructor will automatically be called when we create a child object
{
ID = 0;
}
public Parent(int Id) // This constructor will automatically be called when we create a child object
{
ID = Id;
}
public virtual void Method1 (string someInput) // The "virtual" keyword allows you to override this method
{
Console.WriteLine("Hi there, this method will be inherited");
Console.WriteLine(someInput);
}
protected void Method2 ()
{
Console.WriteLine("Hi there, this method will also be inherited");
}
protected void Method3 ()
{
Console.WriteLine("Hi there, this method will also be inherited");
}
}
// ----- LOWER CLASS ----- //
class Child : Parent
{
pritave int count; // This class has both the "count" and "ID" properties, since the "ID" was inherited
public Parent() // Both the parent and child base constructors are called
{
count = 0;
}
public Parent(int Id) : base (Id) // Both the parent and child second constructors are called
{
count = 0;
}
public override void Method1 (string someInput) // This will override the original Method1 funtion
{
base.Method1 (someInput); // This will call the original method from the parent that now, also belongs to the child
// ... some code ...
}
protected new void Method2 () // This will not override but will instead make it a priority over the other Method2()
{ // This is only used if you create an object like: Parent obj = new Child() and not if you create: Child obj = new Child()
Console.WriteLine("Make it do something different");
}
public sealed override void Method3 () // This "sealed" keyword will stop other subclasses that derive from the child, from overriding this method again
{
Console.WriteLine("Make it do something different");
}
public void Method4 (string someInput, int count)
{
base.Method1 (someInput); //Or just: Method1 (someInput) since, in this case, the methods are different
this.count = count;
}
}