I have 3 classes witch inherit another class called ParentClass
and each of the 3 has the following code inside
public void DrawBackground(Graphics e, Rectangle rect)
{
e.FillRectangle(Brushes.Red, rect);
}
In my main form i have a variable like this ParentClass PClass = new OneOfTheThreeClasses
How can i call the DrawBAckground
method of those classes using that variable, from my form's paint event?
Create either an abstract or virtual method on ParentClass
. Something like this:
public virtual void DrawBackground(Graphics e, Rectangle rect)
{
// do nothing
}
Then in the child classes, override that method:
public override void DrawBackground(Graphics e, Rectangle rect)
{
e.FillRectangle(Brushes.Red, rect);
}
The idea is that ParentClass
needs to define the operations which can be performed on it or any polymorphic version of it (such as a child type). It doesn't necessarily have to provide an implementation (and the definition can be abstract or virtual depending on how ParentClass
itself is implemented and used), but does need to "know" about the method in some way in order for anything to be able to invoke it on an instance of ParentClass
.
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