Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to give access to selective class methods in inheritance?

We have a base class A which consists of 6 public methods :

public class A
{ 
 public void method1()
 {
  // Implementation
 }

 public void method2()
 {
   // Implementation
 }
 .
 . 
 .
 .
 public void method6()
 {
  // Implementation
 }
}

We have two child class B and C which inherits from A. How can I implement it in such a way that Class B has access to only method1(),method2(),method3() and Class C has access to method4(),method5(),method6()??

like image 220
Sriram M Avatar asked Mar 02 '17 12:03

Sriram M


2 Answers

You can't prevent something from using public class A methods, but you can definitely hide them with the proper use of interfaces.

interface IAOne 
{
    void method1();
    void method2();
    void method3();
}

interface IATwo 
{
    void method4();
    void method5();
    void method6();
}

class A : IAOne, IATwo
{
    void method1() { }
    void method2() { }
    void method3() { }
    void method4() { }
    void method5() { }
    void method6() { }
}

So now you have class B which never needs to know about A or about A's methods. It only knows about the IAOne interface. B can now also re-expose any methods (and even re-implement the interface) and delegate the implementation of those to A.

class B : IAOne 
{
    private IAOne _a;
    public B(IAOne a) { _a = a; }

    void method1() { _a.method1(); }
    void method2() { _a.method2(); }
    void method3() { _a.method3(); }
}
like image 181
caesay Avatar answered Oct 28 '22 21:10

caesay


You basically can't do that. The fact that you're attempting to do it should serve as a warning that there is something wrong with your code.

like image 29
Connell.O'Donnell Avatar answered Oct 28 '22 19:10

Connell.O'Donnell