Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting method access in protected section to few classes

Tags:

oop

delphi

I want to limit the access of protected methods to certain inherited classes only.

For example there is a base class like

TBase = Class
  Protected
    Method1;
    Method2;
    Method3;
    Method4;
End;

I have two classes derived from TBase

TDerived1 = Class(TBase)
  //Here i must access only Method1,Method2 and Method3
End;

TDerived2 = Class(TBase)
  //Here i must access only Method3 and Method4
End;

Then is it possible to access only Method1, Method2 and Method3 when i use objects of TDerived1 and Method3 and Method4 when i use objects of TDerived2

like image 657
Bharat Avatar asked Jun 07 '10 15:06

Bharat


2 Answers

There's no way to do that. If a method is protected, then all descendant classes have access to it. You might want to rethink your class design if you have two separate sets of functionality that can be divided that easily.

like image 164
Mason Wheeler Avatar answered Oct 26 '22 23:10

Mason Wheeler


I'd split them, similar to Jeroen's answer:

  TBase = class
  end;

  TBase12 = class(TBase)
  protected
    procedure Method1;
    procedure Method2;
  end;

  TBase34 = class(TBase)
  protected
    procedure Method3;
    procedure Method4;
  end;

  TDerived1 = class(TBase12)
  end;

  TDerived2 = class(TBase34)
  end;

From what you describe, this seems to better model your requirements than a "monolithic" base class (like Mason already wrote).

like image 32
Uli Gerhardt Avatar answered Oct 26 '22 23:10

Uli Gerhardt