access base class variable in derived class

狂风中的少年 提交于 2019-12-05 19:27:33
Furqan Hameedi

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!