You could have seen a object initialization like this
A a = new B();
where B is a derived class of A. But we cannot do the other way around.
B b = new A(); // because A is an abstract class
Take a look into the below example and its output.You can understand how it works.
using System;
using System.Text;
namespace aruns_code
{
class testAbstract
{
[STAThread]
static void Main(string[] args)
{
der derObj = new der();
derObj.nonAbs();
Console.WriteLine("\n\n");
abs absObj = new der();
absObj.nonAbs();
absObj.absMethod();
}
}
class der : abs
{
public der()
{
Console.Write("initialized der\n");
}
public override void absMethod()
{
Console.Write("inside der\n");
}
public new void nonAbs()
{
Console.Write("inside nonAbs of der\n");
}
}
abstract class abs
{
public abs()
{
Console.Write("initialized abs\n");
}
public abstract void absMethod();
public void nonAbs()
{
Console.Write("inside nonAbs of abs\n");
}
}
}
The following is the output.
initialized abs
initialized der
inside nonAbs of der
initialized abs
initialized der
inside nonAbs of abs
inside der
Press any key to continue
See that, when an instance of derived class is created, it’s initializing the base class also. This explains why it happened so!! Also note the selection of methods done here (whether from derived or base class).
Advertisement