This might be a silly question, but I'm a beginner in C#, so please bear with me.
What happens if I name a variable the same in both the base class and the sub class?
For example:
class BaseClass01
{
int x = 10;
}
class SubClass01 : BaseClass01
{
int x = 20;
public int Multiplicative(int a)
{
return x * a;
}
}
if a = 10, the answer I got was 200.
Does this mean variable "int x" in BaseClass01 is different from "int x" in SubClass01? Would anybody be able to provide an example that illustrate the differences?
Thanks in advance for helping me wrap my head around this confusing concept of inheritance!
Edit:
Based on the comments below, I tinkered with the code, and realized that when accessing methods from the base class, the "x" from the subclass does not carry over:
class BaseClass01
{
int x = 10;
public int Subtraction(int a)
{
return a - x;
}
}
class SubClass01 : BaseClass01
{
int x = 20;
public int Multiplicative(int a)
{
x = x * a
return x;
}
}
private void button4_Click(object sender, EventArgs e)
{
SubClass01 sb = new SubClass01();
int answer1 = sb.Multiplicative(10);
int answer2 = sb.Subtraction(answer1);
}
Subtraction() continues to use the "x" value from BaseClass01 (i.e. x remains 10). Using protected keyword avoids the issue entirely.
Thanks for the explanations!
Yes because x in first class is private and drived class can not see it. But if make it (in base class) protected, and use it as this way, compiler gives you a warning:
Warning SubClass01.x hides inherited member BaseClass01 .x. Use the new keyword if hiding was intended.
in fact says you new it, so again is different.
and in this case is better to use new keyword.
Yes they are different fields that happen to have the same unqualified name.
You can think of:
public int Multiplicative(int a) { return x * a; }
as:
public int Multiplicative(int a) { return this.x * a; }
To access the BaseClass01.x, use the base keyword:
public int Multiplicative(int a) { return base.x * a; }
(You'd also need to make BaseClass01.x protected and mark SubClass01.x as new.)
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