質問

Consider we have abstract base class A with virtual method foo1() that is calling some other virtual method foo2().(foo1 and foo2 implemented in base class level but also virtual)

I've also class B which is concrete class that inherits from class A.
Now, Class A had inherited foo1() (and of course foo2(), but if I want to do the same operation of foo1() but this time by calling foo3() instead of foo2(), how can I do that and what is the best practice/design to do so?

I see some options, guess there are better ones

  1. Override foo1() in class B and write same code as in base.foo1() but change calling of foo2() to foo3() --> this is some what code duplication because all code is similar except calling to foo2() or foo3().

  2. Overriding foo2() in concrete class B.
    Is that mean that now inherited foo1() will lunch foo2() overridden version of class B or it will still take implementation of same level class A?

This is the code sample for option 2:(more like pseudo code)

public abstract Class A
{
    public virtual void foo1()
    {
        doing some actions123
        foo2();
        doing some actions4
    }

    public virtual void foo2()
    {
        Console.writeln("Class A foo2");
    }
}

public Class B : A
{
    public override void foo2()
    {
        foo3();
    }

    public void foo3()
    {
        Console.writeln("Class B foo3");
    }
}

public static void main()
{ 
    B bClass = new B();
    B.foo1();
}

Thanks

役に立ちましたか?

解決

Option 2 is the way to go. Override foo2 in class B and whenever foo1 in class A gets called it will then call foo2 in class B.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top