James Lock
James Lock

Reputation: 43

Why the method is not called in the derived class

I have a base class with a virtual method, I overwriting it in the derived class, but nothing happens when executed.

public class Derived : Browser 
{
    private Browser Browser;

    public string UserName;
    public string Password;


    public Derived(string proxy): base(proxy) 
    {
        Browser = new Browser(proxy);
        Browser.InitDriver(false, true);
    }

    protected override void ShowStatus() 
    {
        Debug.WriteLine(this.Status);
    }
}

Base

public class Browser 
{
    private string UserProxy;

    protected string Status = null;

    public Browser(string proxy) 
    {
        UserProxy = proxy;
    }

    protected virtual void ShowStatus() 
    {

    }

    public void InitDriver() 
    {
        Status = "Initializing driver...";
        ShowStatus();
    }
}

When I initialize the derived (new Derived("proxy")) class, the showstatus method is not called.

Upvotes: 1

Views: 428

Answers (2)

Andreas
Andreas

Reputation: 5309

You are creating an instance of Browser not of Derived therfore the call is executed on Browser#ShowStatus and not on Derived#ShowStatus.

public Derived(string proxy): base(proxy) 
{
    Browser = new Browser(proxy);
    Browser.InitDriver(false, true);
}

Just call InitDriver instead of creating a new Browser instance in your constructor:

public Derived(string proxy): base(proxy) 
{
    InitDriver(false, true);
}

Maybe this article could help to understand what the difference between composition (what you are actually doing) and inheritance (what you intended to do) is.

https://www.thoughtworks.com/de/insights/blog/composition-vs-inheritance-how-choose

Upvotes: 3

maccettura
maccettura

Reputation: 10818

Follow your logic, or better yet use your debugger.

When you create a new Derived your constructor does this:

Browser = new Browser(proxy);
Browser.InitDriver(false, true); //This wont compile BTW

Which (once fixed) would call the Browser classes InitDriver() method which contains this code:

Status = "Initializing driver...";
ShowStatus();

The ShowStatus() call is again to the Browser classes implementation of ShowStatus() which does absolutely nothing:

protected virtual void ShowStatus() 
{

}

It is not clear what you want to do, but you could put an abstract method definition in your Browser class so that way the derived class has to implement it. That way your "base" class could call something in the "derived" class.

Upvotes: 1

Related Questions