C # class inheritance and a simple example

public class A { public static int a = 12; public virtual int g() { a--; return h(); } public virtual int h() { a--; return i(); } public int i() { return --a; } } class B : A { public int b = 12; public override int h() { b++; return (a--) + (b++); } public new int i() { return this.g(); } static void Main(string[] args) { Console.WriteLine("A: {0} {1} {2}", new A().g(), new A().h(), new A().i()); Console.WriteLine("B: {0} {1} {2}", new B().g(), new B().h(), new B().i()); Console.ReadLine(); } } 

I found an example, and I was stuck. I know that he will print:

 A: 9 7 6 

but I donโ€™t know why it prints:

 B: 18 17 15 

On track A she g() takes 12 and makes her 11, and then pushes her to h() - then she 10, i() makes her 9 even before she goes anywhere. So this is A : 9 for sure. Then it's the same again, so it's 9 7 and 6. However, on B : it takes the existing a (which is now 6), and g() makes it 5. Then B gets the increment to 13, then 5 + 13 = 18. After that, a = 5 changes to a = 4 and b = 14 . I understand it. But why is it 17 again next? Shouldn't be 18?

+4
source share
3 answers

The main difference in the case of class A member a is static , which means that each instance of class A has the same value, while class B uses the instance variable b , which is reset to the default value (12) for each new instance.

+4
source

calling B().g() creates a new variable b , setting its value to 12 , since you are creating a new object b .

Inside h() , b++ , the value 13 is set, and
return (a--) + (b++) returns 17 because the values โ€‹โ€‹of a and b are 4 and 13.

+1
source

First, weโ€™ll start reading the source step by step. First, look at class A.

  • It has a static integer variable named a containing the value 12
  • There are three functions g(), h() and i()
  • The g() function decreases a by one and calls h() Now the value of a is 11.
  • The h() function decreases a by one and calls i() Now the value of a is 10.
  • Function i() reduces a by one and returns a Now the return value of a is 9.

Now consider class B.

  • It extends from class A.
  • It has an integer variable public (non static) called b containing the value 12.

Well, you found the difference, static, and the other not. This means that all objects a extend from the subtracted value, and all objects b use the reset value once to create the object. You had this error.

0
source

Source: https://habr.com/ru/post/1488324/


All Articles