- If your code permits you can move the implementation of the function to be protected from superclass to subclasses.
- You can setup a new class called the “Mediator” class as a wrapper class which contains the instance to the “A2” class with “private” access and allows only an interface will select methods to be called. Now an Instance of this class can be stored in “A1” to have controlled access for “A1” to “A2”.
Preventing Instances of the subclasses from accessing each others protected methods
7 views (last 30 days)
Show older comments
Hello,
I have two subclasses A1 and A2 that have a common superclass S which is handle class. I have a protected method in the superclass S. Lets call it pm.
In subclass A1, I have a private variable that has a reference to an object of class A2.
I create two objects O1 and O2, where O1 is an instance of A1 and O2 is an instance of A2, respectively. O1 has access to O2 through its private variable I described earlier. I initially thought that O1 can only call the public methods of O2 and the not protected methods, i.e., pm in this case. But it seems that O1 can call the protected methods of O2.
Is there a way to prevent this? I was thinking that despite them sharing a common superclass, instances should only be allowed to acces public methods.
0 Comments
Answers (1)
Adarsh
on 28 Mar 2025
I understand that you want to prevent the access of protected member functions in a subclass “A2” to be restricted from other subclasses “A1” which inherit the same superclass “S”.
According to inheritance rules in Object Oriented programming, a protected member of the superclass can be accessed from the superclass and any of the subclasses, so you cannot directly restrict this access using Access modifiers.
However, there are few alternative ways in which you can restrict this access, they are:
The example implementation for the second method is as follows:
% Middle Person class for A2
classdef A2Mediator
properties (Access = private)
a2Instance
end
methods
function obj = A2Mediator(a2)
obj.a2Instance = a2;
end
function publicMethod(obj)
obj.a2Instance.publicMethod();
end
function safePmAccess(obj)
obj.a2Instance.safePmAccess();
end
end
end
This mediator interface only allows required functions to be visible for outside to access which can easily be controlled.
For more information regarding the “Subclassing” and “Inheritance” please refer to the following documentation link:
I hope this helps.
0 Comments
See Also
Categories
Find more on Assembly in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!