Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble with inheritance

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

Trouble: I currently have a class I'll call Bob its parent class is Cody, Cody has method call Foo(). I want Bob to have the Foo() method as well, except with a few extra lines of code. I've attempted to do Foo() : base(), however that doesn't seem to work like. Is there some simple solution to this?

like image 906
Matt Avatar asked Jul 28 '26 18:07

Matt


2 Answers

You can override Foo in the derived class and call the overridden base class implementation using 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();
    }
}

Output of 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 a base class, because they have the requirement that the base class constructor must be called before the constructor in the derived class:

class Cody
{
    public Cody()
    {
    }
}

class Bob : Cody
{
    public Bob() : base()
    {
    }
}
like image 152
dtb Avatar answered Jul 30 '26 09:07

dtb


The standard form (without polymorphism) is:

class Cody
{
    public void Foo () 
    {
    }
}

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

If you want polymorphism, the following 2 lines change:

// Cody
 public virtual void Foo () 

// Bob 
public override void Foo()

The difference shows when calling on a Bob instance through a Cody reference:

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

b.Foo();    // always Bob.Foo()
c.Foo();    // when virtual, Bob.Foo(), else Cody.Foo()
like image 25
Henk Holterman Avatar answered Jul 30 '26 09:07

Henk Holterman