开发者

access base class variable in derived class

class Program
{
    static void Main(string[] args)
    {
        baseClass obj = new baseClass();
        obj.intF = 5;
        obj.intS = 4;
        child obj1 = new child();
        Console.WriteLine(Convert.ToString(obj.addNo()));
        Console.WriteLine(Convert.ToString(obj1.add()));
        Console.ReadLine();
    }
}
public class baseClass
{
    public int intF = 0, intS = 0;
    public int addNo()
    {
        int intReturn = 0;
        intReturn = intF + intS;
        return intReturn;
    }
}
class child : baseClass
{
    public int add()
    {
        int intReturn 开发者_如何转开发= 0;
        intReturn = base.intF * base.intS;
        return intReturn;
    }
}

I want to access intF and intS in child class whatever i input.. but i always get the values of both variables 0. 0 is default value of both variables.

Can anyone tell me that how can i get the value???

thx in adv..


Yes, Zero is what you should get, since you made single instance of child class and did not assign any value to its inherited variables,

child obj1 = new child();

rather you have instantiated another instance of base class separately and assign value to its members,

baseClass obj = new baseClass();

both runtime both the base class instance and child instance are totally different objects, so you should assign the child values separately like

obj1.intF = 5;
obj1.intS = 4;

then only you shall get the desired result.


You've got two separate objects - that's the problem. The values of the base class variables in the object referred to by obj1 are 0, because they haven't been set to anything else. There's nothing to tie that object to the object referred to by obj.

If you need to access the variables of another object, you'd have to make that object available to the one trying to access the data. You could pass obj as an argument to a method, or perhaps make it a property. There are lots of different approaches here, but we don't know what the bigger picture is - what you're really trying to do. Once you understand why it's not working as you expect it to, you can start thinking about what you're really trying to do.

Just to be clear, this has nothing to do with inheritance. It has everything to do with you creating two distinct objects. You'd get the same effect if you just used a single class, but created two different instances of that class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜