How to change variable value in base class?
-
I have a class that derives from a base class. I can access the member of the base class but the derived class treats it as it's own variable. How do I change the value of the base class variable? For example (C# Example) class A { public int value = 0; public void Display() { Console.WriteLine(value); } } class B : A { public void Update() { base.value++; } } // Main { A aClass = new A(); B bClass = new B(); bClass.Update(); a.Class.Display(); } // Result = 0. I want the result to be 1. How come I can't directly change the value of the base class?
-
Answer:
aClass is an instance of class A. bClass is an instance of class B, which extends class A. So you have two instances of class A, one a pure instance called aClass, one the base class for bClass. When you call bClass.Update() you increment the value inside its base class, not in the separate instance belonging to aClass. Two ways you could change that behaviour are: 1. Call bClass.Display() rather than aClass.Display() 2. Declare value using "public static int value = 0;", the static keyword says value belongs to the class A itself, not to instance of class A. The second option is unlikely to be what you want.
Petze at Yahoo! Answers Visit the source
Other answers
You have mistaken, bClass.Display() will give you what you want
James Bond
Related Q & A:
- How to return a value from .ashx file to javascript in a variable?Best solution by forums.asp.net
- How to pass javascript jQuery variable value in php array?Best solution by Stack Overflow
- how to How to change button properties from another class?Best solution by stackoverflow.com
- How to create variable from value in variable?Best solution by Stack Overflow
- How to change input value in formly?Best solution by Stack Overflow
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.