My understanding is that it is possible to Override a method (marked as Virtual
) in a base class from a derived class using the keywords override
.
But what about overriding a method in the same class?
In my specific case, I have a class x
with 2 methods. Method a
has some common behavior with b
, and b
adds functionality to method a
.
In the past, I have duplicated the code of a
in b
and added the new functionality into b
.
I would like to know if there is a better approach so I can centralize the behavior of method a
.
public class x
{
public static void a() {}
public static void b() {}
}
You could simply call your method a()
from within your method b()
. No need (and no way) to override a method.
public class x
{
private static int _i = 0;
public static void a() {
_i = 1;
}
public static void b() {
a();
// here is _i = 1;
}
}
On the other hand you could have parameter overloads for your method.
public class x
{
private static int _i = 0;
public static void a() {
a(1);
}
public static void a(int i) {
_i = t;
// common code which can use _i
}
}
In this case you can call a(1)
or a()
with the same result.
You can't override in the same class, you only do that in the derived class. You could put the common behavior of your method in method a and then call it from method b.
public static void a()
{
// some common functionality
}
public static void b()
{
// do something
a(); //call a
//do something else
}
You're free to call a from within b as many times as needed.
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