开发者

Calling an overridden method from base constructor

开发者 https://www.devze.com 2023-02-02 04:37 出处:网络
We have a class like this: class LogAnalyzer { protected IExtensionManager manager; publicLogAnalyzer() { GetManager();

We have a class like this:

class LogAnalyzer
    {
        protected IExtensionManager manager;

        public  LogAnalyzer()
        {
            GetManager();
        }

        protected virtual void GetManager()
        {
            manager = new FileExtensionManager();
        }
    }

And we derive another class like this:

class TestableLogAnalyzer:LogAnalyzer
    {
        protected override void GetManager()
        {
            this.manager = new StubExtensionManager();
        }
    }

When we instantiate the child class what's supposed to happen in OOP rules? Does the virtual or the overridden method gets called and why? I tested it in C# and overridden method worked but I suspect it may be the other way around in an interpreted language开发者_JAVA百科. Is that true?


It's not simple to provide a language agnostic answer to this, because "what happens" depends on the language itself. In Java, for instance, the overridden (virtual) method will be called, but this can present its own problems, and is thus not recommended.

You need to consult the documentation or language specification you're interested in, and then read around to see if anyone's published an opinion on why you should or shouldn't do it, and what might go wrong, such as the Scott Meyers piece that AraK links to in his/her comment.


Since it's language agnostic, I'll use C++ as a base and will hope that the advice can be extrapolated.

Constructor of LogAnalyser is called before constructor of TestableAnalyser. This means that during its work TestableAnalyser is not constructed yet, thus calling virtual methods can be dangerous (they may use uninitialized data).

In your case derived class wants to affect initialization of its base class. Virtual methods overriding is not the only way to do this. You can create one more constructor which accepts manager, derived classes will pass "new StubExtensionManager();".

0

精彩评论

暂无评论...
验证码 换一张
取 消