Consider the following MATLAB class definition and usage:
classdef MyClass
properties (Access = private)
secret = 42;
end
methods
function val = getSecret(obj)
val = obj.secret;
end
end
end
obj = MyClass();
disp(obj.getSecret());What will be printed when running this code?
classdef MyClass
properties (Access = private)
secret = 42;
end
methods
function val = getSecret(obj)
val = obj.secret;
end
end
end
obj = MyClass();
disp(obj.getSecret());Private properties can be accessed inside class methods.
The property secret is private, so it cannot be accessed directly outside the class. However, the method getSecret is inside the class and can access it. Thus, calling obj.getSecret() returns 42.
Given this MATLAB class:
classdef MyClass
properties (Access = protected)
data = 10;
end
end
obj = MyClass();
disp(obj.data);What will be the result of running this code?
classdef MyClass
properties (Access = protected)
data = 10;
end
end
obj = MyClass();
disp(obj.data);Protected properties are accessible only within the class and subclasses.
The property data is protected, so it cannot be accessed directly from outside the class. Attempting to do so causes an error.
Examine this MATLAB class and script:
classdef MyClass
methods (Access = private)
function secretMethod(obj)
disp('Secret method called');
end
end
methods
function callSecret(obj)
obj.secretMethod();
end
end
end
obj = MyClass();
obj.secretMethod();Why does the last line cause an error?
classdef MyClass
methods (Access = private)
function secretMethod(obj)
disp('Secret method called');
end
end
methods
function callSecret(obj)
obj.secretMethod();
end
end
end
obj = MyClass();
obj.secretMethod();Think about where private methods can be accessed.
Private methods are only accessible inside the class methods. Calling obj.secretMethod() from outside the class causes an access error.
Consider these MATLAB classes:
classdef ParentClass
properties (Access = protected)
value = 5;
end
end
classdef ChildClass < ParentClass
methods
function v = getValue(obj)
v = obj.value;
end
end
end
obj = ChildClass();
disp(obj.getValue());What will be printed?
classdef ParentClass
properties (Access = protected)
value = 5;
end
end
classdef ChildClass < ParentClass
methods
function v = getValue(obj)
v = obj.value;
end
end
end
obj = ChildClass();
disp(obj.getValue());Protected properties are accessible in subclasses.
The subclass ChildClass inherits the protected property value and can access it inside its methods. So getValue returns 5.
In MATLAB, which property access level restricts access to the class itself and any subclasses, but not from outside these classes?
Think about access levels that allow inheritance but restrict external access.
Protected access allows properties and methods to be accessed within the class and subclasses only. Private restricts access to the class itself only. Public allows access from anywhere. Global is not an access level in MATLAB classes.
