Reputation: 60691
A coworker introduced me to the concept of hiding implementation details through allowing the derived class to override the private field initializations.
For example I have a base class:
public class Animal
{
private Dog dog;
private Cat cat;
private Mouse mouse;
protected virtual void Init()
{
dog = new Dog();
cat = new Cat();
mouse = new Mouse();
}
public void DoStuff() {}
}
This allows me to override the initialization within a derived class of the base class privates:
public class Cookie : Animal
{
protected override void init()
{
//do whatever i want here
}
}
What am I trying to achieve?
I have a class (animal in the example above) that has about 20 private objects that need to be initialized, and I want to be able to define my own way of initializing them specifically when doing unit testing.
Upvotes: 0
Views: 415
Reputation: 2602
1) This is simply overriding, i am not aware that it is more than that. But you cannot access private fields in a subclass, they have to be protected as well so you can access them in your subclass.
2) Your question is not clear, but i am guessing you are asking how you can call the method of the base class from within the override. all you need to do is
public class Cookie : Animal
{
protected override void init()
{
//do whatever you want here
base.init(); //This line will call the init() function in Animal.
//do whatever you want here
}
}
Upvotes: 2
Reputation: 6522
That is simply called override
.
An override method provides a new implementation of a member that is inherited from a base class.
You can invoke the base class
' overriden method
Init()
from the derived class
by using base.Init();
.
Upvotes: 1