In one base class, there's a protected procedure. When inheriting that class, I want to hide that procedure from being used from the outside. I tried overriding it from within the private and even strict private sections, but it can still be called from the outside. The Original class is not mine, so I can't change how TOriginal is defined.

Is it possible to hide this procedure in my inherited class? And how?

type
  TOriginal = class(TObject)
  protected
    procedure SomeProc;
  end;

  TNew = class(TOriginal)
  strict private
    procedure SomeProc; override;
  end;
有帮助吗?

解决方案

Protected methods are already hidden from the outside. (Mostly; see below.) You cannot reduce the visibility of a class member. If the base class declared the method protected, then all descendants of that class may use the method.


In Delphi, other code within the same unit as a class may access that class's protected members, even code from unrelated classes. That can be useful sometimes, but usually to work around other design deficiencies. If you have something that's "really, really" supposed to be protected, you can make it strict protected, and then the special same-unit access rule doesn't apply.

其他提示

Once exposed you can not hide it but you can do this to spot where it is called in limit way

TOriginalClass = class
public
  procedure Foo;
end;

TNewClass = class(TOriginalClass) 
public
  procedure Foo; reintroduce;
end;

implementation

procedure TNewClass.Foo;
begin
  Assert(False, 'Do not call Foo from this class');
  inherited Foo;
end;

var Obj: TNewClass;
Obj := TNewClass.Create;
Obj.Foo; // get assert message

Will not get Assert error if declared as TOriginalClass
var Obj: TOriginalClass;
Obj := TNewClass.Create;
Obj.Foo; // Never get the assert message
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top