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
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
}
}
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();.
Hi I have an abstract class in which I have some public methods and some abstract ones.
I have the public so that they implement the common methods for the derived classes.
What is confusing me is why I will want to define a public abstract method instead of protected abstract. That makes no sense to me to define a public abstract method in abstract class.... because if is an abstract will be overridden, in the derived classes, but the same is if is defined as public but somehow it makes more sense to define it as protected as we know that we will override that in the derived classes.
Is it wrong to define the method as public abstract in an abstract class? Which is better and why?
It depends on what you want to achieve. For example, you have a Television class that has 3 methods, TurnOn, TurnOff, and Draw.
You only want clients to TurnOn or TurnOff the TV but only its subclass should know what and how to Draw on the screen. So, Television will look more or less like below.
public abstract class Television
{
public abstract void TurnOn();
public abstract void TurnOff();
protected abstract void Draw();
}
Then each company has its own implementation.
public sealed class MyTelevision
: Television
{
public override void TurnOn()
{
Console.WriteLine("Turn on my tv");
}
public override void TurnOff()
{
Console.WriteLine("Turn off my tv");
}
protected override void Draw()
{
// code here.
}
}
Clients can TurnOn or TurnOff a TV but cannot Draw anything on the screen.
For the same reason you want a public method in an object :)
You just don't know the particular implementation at this stage.
It is common in classes with very high level of abstraction, middlewares for example.
Edit: It is 100% legal. You just need to be sure that it is functionality that you want to expose to the rest of the world in every concrete implementation. Entry point methods (ex: start, execute, parse..) are usually of this kind.
The Abstract Class itself has to be as accessible as the Classes, which inherit from it. So if the inherited Classes are Public, the Abstract Class has to be public too.
Public Abstract has the same Idea like other Public Methods: If you have a Abstract Class, you will pass this arround. So if this Method should get called from outside, it's public. If the method is just for communication between Child and Parent, protected is the way to go. Easy example, see the Main-Method as the user of the abstract class:
static void Main(string[] args)
{
Animal cat = new Cat();
Animal dog = new Dog();
cat.Eat();
dog.Eat();
cat.Move();
dog.Move();
}
public abstract class Animal
{
public abstract void Eat();
protected abstract void ComplexMoving();
public void Move()
{
ComplexMoving();
}
}
public class Dog : Animal
{
public override void Eat()
{
Debug.WriteLine("Dog says Namnam");
}
protected override void ComplexMoving()
{
Debug.WriteLine("Dog no stupid");
}
}
public class Cat: Animal
{
public override void Eat()
{
Debug.WriteLine("Cat says namnam");
}
protected override void ComplexMoving()
{
Debug.WriteLine("Cat does a slalom");
}
}
TLTR: because of Open-Close principle.
Why it makes sense to have abstract members protected instead of public is, from what I can see, to hide "implementation details". It is convenient to expose one single "entry point" if you want to ensure that the intent of which each abstract member is defined inside the class is preserved. Normally, it is the public method which will orchestrate when and what abstract members are called or accessed and in what particular order and under what circumstances, but the tradeoff for this layer of encapsulation is that you lose the extensibility property.
Explanation:
Suppose we create a library with multiple exception handler classes.
Initial implementation:
namespace MyLibrary;
public abstract class ExceptionHandlerBase
{
protected abstract void HandleException(Exception ex, Action operation);
public void Execute(Action operation)
{
try {
operation.Invoke();
} catch(Exception ex) {
this.HandleException(ex, operation);
}
}
}
public class InputExceptionHandler: ExceptionHandlerBase
{
protected override void HandleException(Exception ex, Action operation)
{
throw new Exception(
message: "Wrong input" // or whatever...
inner: ex);
}
}
public class DbExceptionHandler : ExceptionHandlerBase
{
protected override void HandleException(Exception ex, Action operation)
{
Console.WriteLine("Failed to connect to database. Retrying...");
operation.Invoke();
}
}
Now, if we want to extend the behavior of ExceptionHandlerBase we will see that we are limited because of that protected access modifier of ExceptionHandlerBase.HandleException method.
Let's try to add a hook before ExceptionHandlerBase.HandleException method:
class ExceptionHandlerWrapper : ExceptionHandlerBase
{
readonly ExceptionHandlerBase _base;
public ExceptionHandlerWrapper(ExceptionHandlerBase #base)
{
thos._base = #base;
}
protected override void HandleException(Exception ex, Action operation)
{
this.BeforeHandleException();
this._base.HandleException(ex, operation); // Compile error**
}
private void BeforeHandleException()
{
// do additional stuff
}
}
As you can see, there is a compilation error because ExceptionHandlerBase.HandleException is not accessible from outside the class that defines it.
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()
{
}
}