M
M
Michael Sne Bjorn Palagin2017-07-14 19:25:29
C++ / C#
Michael Sne Bjorn Palagin, 2017-07-14 19:25:29

C# inheritance. I need your help?

Good afternoon, ladies and gentlemen. I recently started learning the language and programming in general. Here comes the inheritance. Probably a stupid question, so don't swear too much.

Here is the code
class Program
    {
        static void Main(string[] args)
        {
            B b = new B(); // Делаю ссылку на класс B
            
            Console.WriteLine(b.new_age); // Вывожу в консоль переменную new_age из класса B
            Console.ReadKey();
        }
    }

    class A 
    {
        protected int age = 20; // Создаю протектед переменную со значением 20
    }

    class B : A // Создаю класс B который наследуется от класса A
    {
        public int new_age; // Создаю публичную переменную new_age

        public void newMethod() // Создаю публичный метод
        {
            new_age = age; // В методе говорю что новая переменная new_age равна переменной age из класса А
        }                
    }

And the question is why the value 0 is displayed in the console, and not 20. After all, in class B I made it clear that the new_age variable is equal to the age variable from class A, that is, it takes the value 20. And calling it in the Main method in the console, it should show not 0, but 20.
Can you briefly talk about what I did not understand. :(

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
kvasek, 2017-07-14
@ven000mus

You didn't call newMethod and no value was assigned.

static void Main(string[] args)
        {
            B b = new B(); // Делаю ссылку на класс B
            <b>b.newMethod();</b>

            Console.WriteLine(b.new_age); // Вывожу в консоль переменную new_age из класса B
            Console.ReadKey();
        }

I assume that you have confused newMethod with a constructor.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question