Inheritance problem

I'm relatively new to programming, so excuse me if I get some of the terms wrong (I learned the concepts, I just didn't use most of them).

Problem: I currently have a class that I will call Bob, its parent class is Cody, Cody has a method to call Foo (). I want Bob to also have a Foo () method, with the exception of a few extra lines of code. I tried to do Foo (): base (), however this does not seem to work. Is there any simple solution?

+3
source share
3 answers

You can override Fooin a derived class and invoke an overridden implementation of the base class with base.Foo():

class Cody
{
    public virtual void Foo()
    {
        Console.WriteLine("Cody says: Hello World!");
    }
}

class Bob : Cody
{
    public override void Foo()
    {
        base.Foo();
        Console.WriteLine("Bob says: Hello World!");
        base.Foo();
    }
}

Conclusion new Bob().Foo():

Cody says: Hello World!
Bob says: Hello World!
Cody says: Hello World!

Constructors use a slightly different syntax to call the constructor in the base class, since they require that the constructor of the base class be called before the constructor in the derived class:

class Cody
{
    public Cody()
    {
    }
}

class Bob : Cody
{
    public Bob() : base()
    {
    }
}
+8
source

Standard form (without polymorphism):

class Cody
{
    public void Foo () 
    {
    }
}

class Bob : Cody
{
    public new void Foo()
    {
        base.Foo(); // Cody.Foo()
        // extra stuff
    }
}

If you need polymorphism, the following 2 lines change:

// Cody
 public virtual void Foo () 

// Bob 
public override void Foo()

The difference is displayed when calling the Bob instance via the Cody link:

Bob b = new Bob();
Cody c = b;

b.Foo();    // always Bob.Foo()
c.Foo();    // when virtual, Bob.Foo(), else Cody.Foo()
+2
source

, , . "", .

class Bob
{
  public virtual void Foo()
  {

  }
}

class Cody
{
  public override void Foo()
  {
    base.Foo()
    // your code
  }
}
0

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


All Articles