Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exposing only some inherited methods in the derived class

I stumbled across an interview question related to OOPS. Here is the question: There is a base class A with 5 methods. Now how should I design the class such that if a class B inherits class A, only 3 methods are exposed. And if a class C inherits class A, the rest of the 2 methods are exposed.

Any thoughts ??

like image 870
iJade Avatar asked Feb 11 '23 01:02

iJade


2 Answers

if A is partial and you have 2 namespaces then:

namespace the_impossible
{
class Program
{
    static void Main(string[] args)
    {
        B b = new B();
        C c = new C();

        b.m1();
        b.m2();
        b.m3();

        c.m4();
        c.m5();
    }
}

namespace A_1
{
    public partial class A
    {
        public  void m1() { }
        public  void m2() { }
        public  void m3() { }
    }
}

namespace A_2
{
    public partial class A
    {
        public void m4() { }
        public void m5() { }
    }
}

class B : A_1.A 
{

}

class C : A_2.A
{ 

}
}

enter image description hereenter image description here

like image 197
RadioSpace Avatar answered Feb 13 '23 04:02

RadioSpace


It should not be possible in any object-oriented language, otherwise it would break the Liskov substitution principle. Substituting a B for an A should not reduce its correctness (meaning methods should not suddenly be unavailable)

However, there is still some ambiguity in the question that allows for some "out-of-the-box" thinking. Here are questions I would pose back to the interviewer:

  • What do you mean by "exposed"?
  • Do the 5 methods in A have to be public?
  • Does the "exposition" by C need to be implicit or can the be explicitly exposed (e.g. pass-through)

Based on those answers you could either come up with possible options using internal, explicit interface implementations, etc.

like image 37
D Stanley Avatar answered Feb 13 '23 02:02

D Stanley