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
}
}
Does this type of implementation-detail-hiding have a name?
Would I ever call Init() from Animal or does this pattern insist on Init() because called from a derived class?
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.
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
}
}
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();.
Related
I was working on a certain problem and found some interesting problem inside.
Let me explain with an example (C# code)
public class A: IA
{
protected abstract void Append(LoggingEvent loggingEvent)
{
//Some definition
}
}
public class B: A
{
protected override void Append(LoggingEvent loggingEvent)
{
//override definition
}
}
public class MyClass: B
{
//Here I want to change the definition of Append method.
}
Class A and B are of a certain library and I don't have any control to change those classes.
Since none of the methods in the hierarchy here are sealed, you can just continue overriding the method yourself:
public class MyClass: B
{
protected override void Append(LoggingEvent loggingEvent)
{
// New logic goes here...
}
}
I have shared the solution below based as per my research, but made few following changes to the code you shared based on my perception, since the code in the question is not valid at few occasions.
Added an empty Interface IA, as Class A is not implementing any public method.
Defined Class A as abstract, as any non-abstract class cannot define a abstract method.
Removed the body for Append method inside Class A, as a abstract method cannot have a body.
public interface IA
{
}
public abstract class A : IA
{
protected abstract void Append();
}
public class B : A
{
protected override void Append()
{
//override definition
}
}
public class MyClass : B
{
//Here I want to change the definition of Append method.
//You can do is hide the method by creating a new method with the same name
public new void Append() { }
}
Answer : You cannot override a non-virtual method. The closest thing you can do is hide the method by creating a new method with the same name but this is not advisable as it breaks good design principles.
But even hiding a method won't give you execution time polymorphic dispatch of method calls like a true virtual method call would.
I have a C# application; There is a parent class with many child classes. I would like a method in the parent class with some logic in it, and have custom logic added to it by each child class, so that when any child class calls the method, it first runs some code defined in the parent class, and then runs the customized part of it as defined in the child class. Can this be done? If not, what is the best way to achieve this kind of code execution?
Yes, this can be done by defining a virtual method in the base class, and calling it from your "payload" method at the spot where the custom logic needs to be "plugged in". It is common to make this method abstract:
abstract class MyBase {
protected abstract void CustomLogic(); // Subclasses implement this
public void PayloadMethod() {
... // Do somethig
CustomLogic();
... // Do something else
}
}
class Derived1 : MyBase {
protected override void CustomLogic() {
... // Custom logic 1
}
}
class Derived2 : MyBase {
protected override void CustomLogic() {
... // Custom logic 2
}
}
class Derived3 : MyBase {
protected override void CustomLogic() {
... // Custom logic 3
}
}
Clients of your class hierarchy instantiate one of DerivedN classes, and call PayloadMethod(), which calls CustomLogic as part of its invocation.
This approach is called Template Method Pattern.
One way to achieve it is define a non virtual method as entry point that execute the code defined in the base class and then call a virtual (or abstract) protected method that child class can (or must) override, like this:
abstract class Foo
{
public void Bar()
{
// some code defined in the parent class
BarCore(); // the customized part of it as defined in the child class
}
protected virtual void BarCore() { }
}
The easiest way to achieve this is to have two methods:
class BaseClass
{
public void DoSomething()
{
// base class code
// derived class code, modifiable by the derived class
this.DoItSpecificallyForThatDerivedClass();
}
protected abstract void DoItSpecificallyForThatDerivedClass();
}
public class ADerivedClass : BaseClass
{
protected override void DoItSpecificallyForThatDerivedClass()
{
// code specific to this instance and/or class
}
}
Can someone explain the difference between an override and just a normal method, and when an override should be used over the latter?
Every tutorial I have found uses words like "Polymorphism" and "Derived Classes" rather than just explain their application and when they should be used.
I am using C# in particular but an understanding of overrides as a concept would be very helpful.
Thanks for any input on the subject.
Simply put, overrides are for when you want to change the behavior of a method in a derived class. For example, say you had an Animal.Speak() method:
class Animal
{
public virtual void Speak()
{
Console.WriteLine("The animal makes random animal noises.");
}
}
Now, if you had a specific type of animal, you'd want to override that Speak() method to make noises that that type of animal would make:
class Dog : Animal
{
public override void Speak()
{
Console.WriteLine("The dog barks.");
}
}
Now if you make a Dog object and tell it to speak, it will bark. Now let's consider if you had a Cat class but didn't override the Speak() method:
class Cat : Animal
{
}
If you had this code:
Animal dog = new Dog();
Animal cat = new Cat();
dog.Speak();
cat.Speak();
You'd see this:
The dog barks.
The animal makes random animal noises.
For example, if there is an predefined class which has a method "ABC" and you want to change its behavior. In that case you have to write the keyword override before the method ABC that you want to change from its default to what you really want to have. Simple words use override when you have to change already existing method. Do not use override when you are creating a new method of any object which already does not exists.
Overriding occurs when you make a method/function/subroutine that has the same name as another function, but has different functionality. One prominent example is the Equals method. This method can be overridden for a custom object to return your concept of equality. For example, if you have a Person object and decide that 2 Persons are equal when they have the same name, you could override the existing Equals method to return whether or not 2 Persons have the same name. Good luck!
What do you mean by "overriden" method?
There are two options:
Override virtual methods in subclasses. Here "method overriding" is a part of polymorphism - one of the concept of object-oriented programming.
For instance, here you have a base class A with some virtual methods:
public class A
{
public void Method1() {}
public virtual void Method2() {}
public virtual void Method3() {}
}
If you create class B, which is derived from A you will have an opportunity to override virtual methods in such case:
public class B : A
{
public override void Method2() {}
public override void Method3() {}
}
In such way you change your base functionality from class A by your new functionality from class B.
So, when you call method from instance of class B , you will get functionality from overriden method in class B:
B instanceB = new B();
instanceB.Method2();
Override method signature. Here you are able to have multiple methods with same name, but with different signatures.
For example, you have such class with 3 methods, which have one name TestMethod, but there are different signatures (different input and output parameter types):
public class TestClass
{
public void TestMethod() {}
public int TestMethod(int value) {}
public string TestMethod(int value) {}
}
I noticed that DrawableGameComponent could be used for "instance class"
DrawableGameComponent contain some "overrides" such as Draw, LoadContent, Update etc...
take a look at this code below:
this is the class of Game1:
public class Game1 : Microsoft.Xna.Framework.Game
{
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Contenttt";
graphics.PreferredBackBufferWidth = GAME_WIDTH;
graphics.PreferredBackBufferHeight = GAME_HEIGHT;
}
}
the code of my other class:
public class Bullet: DrawableGameComponent //based by DrawableGameComponent
{
public Bullet(Game1 game): base(game) //set argument for draablegamecomponent
{
//do something
}
}
DrawableGameComponent:
public DrawableGameComponent (Game game )
parameter description:
game
Type: Game
The Game that the game component should be attached to.**
As you can see, the parameter of DrawableGameComponent is a class of Microsoft.Xna.Framework.Game. then we fill it with our Game1 class.
this is the code of my other class and will impact in my World Game1
the override by DrawableGameComponent
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
}
protected override void UnloadContent()
{
}
The question are:
why do we can use their "overrides" on my own class?
why is this would impact the game1 world?
Whereas, in c# a "base" statement just like
public class Bullet: MyClass
we can't make it based "instance" class.
But for DrawableGameComponent, the instance class, they can set it up through their parameter so their "override void" will work on class of parameter that we put before.
If you know how the way, please let me know how to make the class.
It sounds like you might not understand the idea of a virtual method. The ability to override methods is available because methods defined in the base class are marked as virtual. Basically these are examples of the Template Method design pattern. virtual or abstract methods allow their implemntation to change in subclasses (or in the case of an abstract class, be completely deffered).
public abstract class BaseClass
{
public void TemplateMethod()
{
DoSomething();
DoSomethingElse();
}
protected virtual void DoSomething()
{
// implementation that can be changed or extended
}
// no implementation; an implementation must be provided in the inheritor
protected abstract void DoSomethingElse();
}
public sealed class SubClass : BaseClass
{
protected override DoSomething()
{
// add extra implementation before
base.DoSomething(); // optionally use base class' implementation
// add extra implementation after
}
protected override DoSomethingElse()
{
// write an implementation, since one did not exist in the base
}
}
Then you can do the following:
SubClass subClass = new SubClass();
// will call the new implementations of DoSomething and DoSomethingElse
subClass.TemplateMethod();
See Also:
Inheritance
Virtual Methods
Template Method Pattern
I have a base class and a class inheriting base. The base class has several virtual functions that the inherited class may override. However, the virtual functions in the base class has code that MUST to run before the inherited class overrides get called. Is there some way that I can call the base classes virtual functions first then the inherited class overrides. Without making a call to base.function().
I know I can simply make two functions, one that gets called, the other virtual. But is there a way I can keep the same names as well? I know I may need to change some things around.
class myBase
{
public virtual myFunction()
{ /* must-run code, Called first */ }
}
class myInherited : myBase
{
public override myFunction()
{ /* don't use base.myFunction();,
called from base.myFunction(); */ }
}
Similar question here.
C# doesn't have support for automatically enforcing this, but
you can enforce it by using the template method pattern. For example, imagine you had this code:
abstract class Animal
{
public virtual void Speak()
{
Console.WriteLine("I'm an animal.");
}
}
class Dog : Animal
{
public override void Speak()
{
base.Speak();
Console.WriteLine("I'm a dog.");
}
}
The trouble here is that any class inheriting from Animal needs to call base.Speak(); to ensure the base behavior is executed. You can automatically enforce this by taking the following (slightly different) approach:
abstract class Animal
{
public void Speak()
{
Console.WriteLine("I'm an animal.");
DoSpeak();
}
protected abstract void DoSpeak();
}
class Dog : Animal
{
protected override void DoSpeak()
{
Console.WriteLine("I'm a dog.");
}
}
In this case, clients still only see the polymorphic Speak method, but the Animal.Speak behavior is guaranteed to execute. The problem is that if you have further inheritance (e.g. class Dachshund : Dog), you have to create yet another abstract method if you want Dog.Speak to be guaranteed to execute.
A common solution that can be found in the .NET Framework is to split a method in a public method XXX and a protected, virtual method OnXXX that is called by the public method. For your example, it would look like this:
class MyBase
{
public void MyMethod()
{
// do something
OnMyMethod();
// do something
}
protected virtual void OnMyMethod()
{
}
}
and
class MyInherited : MyBase
{
protected override void OnMyMethod()
{
// do something
}
}
public abstract class BaseTemp
{
public void printBase() {
Console.WriteLine("base");
print();
}
public abstract void print();
}
public class TempA: BaseTemp
{
public override void print()
{
Console.WriteLine("TempA");
}
}
public class TempB: BaseTemp
{
public override void print()
{
Console.WriteLine("TempB");
}
}
There is no way to do what you're seeking other than the 2 ways you already named.
Either you make 2 functions in the base class, one that gets called and the other virtual.
Or you call base.functionName in the sub-class.
Not exactly. But I've done something similar using abstract methods.
Abstract methods must be overriden by derived classes. Abstract procs are virtual so you can be sure that when the base class calls them the derived class's version is called. Then have your base class's "Must Run Code" call the abstract proc after running. voila, your base class's code always runs first (make sure the base class proc is no longer virtual) followed by your derived class's code.
class myBase
{
public /* virtual */ myFunction() // remove virtual as we always want base class's function called here
{ /* must-run code, Called first */
// call derived object's code
myDerivedMustcallFunction();
}
public abstract myDerivedMustCallFunction() { /* abstract functions are blank */ }
}
class myInherited : myBase
{
public override myDerivedMustCallFunction()
{ /* code to be run in derived class here */ }
}
What do you think of this?
class myBase
{
public void myFunctionWrapper()
{
// do stuff that must happen first
// then call overridden function
this.myFunction();
}
public virtual void myFunction(){
// default implementation that can be overriden
}
}
class myInherited : myBase
{
public override void myFunction()
{
}
}