D
D
Denis Bredun2021-07-25 16:21:46
C++ / C#
Denis Bredun, 2021-07-25 16:21:46

The ban on overriding methods does not work. Why?

There is a code where I override methods:

class Program
  {
    static void Main(string[] args)
    {
      Person p1 = new Person("Bill");
      p1.Display(); // вызов метода Display из класса Person

      Employee p2 = new Employee("Tom", "Microsoft");
      p2.Display(); // вызов метода Display из класса Employee

      Person p3 = new Employee("Bill", "Microsoft");
      p3.Display(); 

      Console.ReadKey();
    }
  }
  class Person
  {
    public string Name { get; set; }
    public Person(string name)
    {
      Name = name;
    }
    public virtual void Display()
    {
      Console.WriteLine(Name);
    }
  }
  class Employee : Person
  {
    public string Company { get; set; }

    public Employee(string name, string company)
                : base(name)
    {
      Company = company;
    }

    public override void Display()
    {
      Console.WriteLine($"{Name} работает в {Company}");
    }
  }

Conclusion:

Bill
Tom works at Microsoft
Bill works at Microsoft

I'm trying to put a ban on redefinition:
class Program
  {
    static void Main(string[] args)
    {
      Person p1 = new Person("Bill");
      p1.Display(); // вызов метода Display из класса Person

      Employee p2 = new Employee("Tom", "Microsoft");
      p2.Display(); // вызов метода Display из класса Employee

      Person p3 = new Employee("Bill", "Microsoft");
      p3.Display(); 

      Console.ReadKey();
    }
  }
  class Person
  {
    public string Name { get; set; }
    public Person(string name)
    {
      Name = name;
    }
    public virtual void Display()
    {
      Console.WriteLine(Name);
    }
  }
  class Employee : Person
  {
    public string Company { get; set; }

    public Employee(string name, string company)
                : base(name)
    {
      Company = company;
    }

    public override <b><i>sealed </i></b> void Display()
    {
      Console.WriteLine($"{Name} работает в {Company}");
    }
  }

Conclusion:

Bill
Tom works at Microsoft
Bill works at Microsoft

Although, in theory, it should be:

Bill
Tom works at Microsoft
Bill

For I put a ban on redefinition.
Either it doesn't work right, or I'm doing something wrong, or I don't really understand how it works and/or should work.
Explain please =)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Bredun, 2021-07-25
@Luffy1

Now I understand why it doesn't work, I'm just stupid:
60fdab22ec3c4423770459.jpeg
60fdab3293d18197304962.png
60fdab7a0d0fd050061824.png

I
Ilya, 2021-07-25
@sarapinit

You misunderstood. The ban on overriding in your case will mean that in a class inherited from Person, it will not be possible to write override.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question