Generally, Constructor is the very first thing to be executed in class when it's instantiated.
But in following case, A member methods of the class are executed first & then the constructor.
Why is it so?
A Code Scenario :
namespace AbsPractice
{
class Program
{
static void Main(string[] args)
{
SavingsCustomer sc = new SavingsCustomer();
CorporateCustomer cc = new CorporateCustomer();
}
}
public abstract class Customer
{
protected Customer()
{
Console.WriteLine("Constructor of Abstract Customer");
Print();
}
protected abstract void Print();
}
public class SavingsCustomer : Customer
{
public SavingsCustomer()
{
Console.WriteLine("Constructor of SavingsCustomer");
}
protected override void Print()
{
Console.WriteLine("Print() Method of SavingsCustomer");
}
}
public class CorporateCustomer : Customer
{
public CorporateCustomer()
{
Console.WriteLine("Constructor of CorporateCustomer");
}
protected override void Print()
{
Console.WriteLine("Print() Method of CorporateCustomer");
}
}
}
Because by using a super class's constructor we can access/initialize private members of a class. A constructor cannot be called as a method. It is called when object of the class is created so it does not make sense of creating child class object using parent class constructor notation.
Constructor is a special non-static member function of a class that is used to initialize objects of its class type. In the definition of a constructor of a class, member initializer list specifies the initializers for direct and virtual bases and non-static data members.
Why? The Sun compiler says, call to super must be first statement in constructor . The Eclipse compiler says, Constructor call must be the first statement in a constructor . So, it is not stopping you from executing logic before the call to super() .
Purpose of Class Constructor Methods A constructor method is a special function that creates an instance of the class. Typically, constructor methods accept input arguments to assign the data stored in properties and return an initialized object.
That's because when you call SavingsCustomer
ctor, first of all its base class ctor is called; in Customer
ctor you call Print
that's an overridden method.
So basicly before SavingsCustomer
ctor instructions are executed, Customer
ctor must be completely called.
Note that when you call Print
from Customer
, SavingsCustomer.Print()
is executed.
This is the expected behaviour; if you want your classes to behave differently, you must change their logic. Maybe you shouldn't call an abstract method from base constructor, just to avoid what you're seeing now...
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