简体   繁体   中英

Selective accessibility of methods in derived classes

Recently I was attending an interview, where interviewer asked a tricky question related to inheritance. Question was based on c#.

We have base class ClassA , and it has two methods - Method1() , Method2() .

public class ClassA {
    void Method1();
    void Method2();
}

Now we inherit this class then create ClassB . Objects of ClassB should have Method1 accessible outside, Method2 should be hidden

public class ClassB : ClassA{
}

ClassB objB= new ClassB();

objB.Method1(); //should be accessible 
objB.Method2(); //should not be accessible. 

Again we create another class ClassC from ClassA . Objects of ClassC should have Method2 accessible outside, Method1 should be hidden

public class ClassC : ClassA{
}

ClassC objC= new ClassC();

objC.Method1(); //should not be accessible 
objC.Method2(); //should be accessible. 

I have answered with private access modifier to the methods accordingly. Interviewer didn't accept. Is there any wiser way to achieve this?

Both methods should be protected in Class A which means that they are only visible internally to the object and to inherited classes.

Then in class B , reintroduce method Method1 and make it public , calling the interited method.

And in class C , reintroduce method Method2 and make it public , calling the interited method.

Use the new keyword when reintroducing methods with existing names to clarify the intention and prevent a compiler warning.

class A
{
    protected void Method1()
    {
    }

    protected void Method2()
    {
    }
}

class B: A
{
    public new void Method1()
    {
        base.Method1();
    }
}

class C : A
{
    public new void Method2()
    {
        base.Method2();
    }
}


class Program
{
    static void Main(string[] args)
    {
        A a = new A();
        a.Method1(); // Not allowed
        a.Method2(); // Not allowed

        B b = new B();
        b.Method1();
        b.Method2(); // Not allowed

        C c = new C();
        c.Method1(); // Not allowed
        c.Method2();
    }
}

Just for completeness and being encouraged to write it up as an answer:

You shouldn't. This design is a code smell. It hints to issues with interface separation (and probably more). So that would be the first thing, I would answer.

But followed by @NineBerry's approach, disclaiming "If I wasn't allowed to review the design and just implement the requirement ..."

Reasoning: The interviewer now knows I am aware of design issues and clean code but also I am proficient enough to do it despite my objections, because after all, there may be situations where a redesign would be out of question for whatever reason.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM