Challenge - 5 Problems
Master of Properties and Methods
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of method accessing property
What is the output of this MATLAB code when calling the method
getArea?MATLAB
classdef Circle
properties
Radius
end
methods
function obj = Circle(r)
obj.Radius = r;
end
function a = getArea(obj)
a = pi * obj.Radius^2;
end
end
end
c = Circle(3);
disp(c.getArea())Attempts:
2 left
💡 Hint
Recall the formula for the area of a circle is pi times radius squared.
✗ Incorrect
The method getArea calculates the area using pi * Radius^2. With Radius = 3, area = pi * 9 = 28.2743 approximately.
❓ Predict Output
intermediateValue of property after method call
What is the value of the property
Count after running this code?MATLAB
classdef Counter
properties
Count = 0;
end
methods
function obj = increment(obj)
obj.Count = obj.Count + 1;
end
end
end
c = Counter();
c = c.increment();
c = c.increment();
disp(c.Count)Attempts:
2 left
💡 Hint
Each call to increment adds 1 to Count.
✗ Incorrect
The increment method adds 1 to Count each time. After two calls, Count is 2.
❓ Predict Output
advancedOutput of method with dependent property
What is the output of
obj.Area after creating the object obj = Rectangle(4,5);?MATLAB
classdef Rectangle
properties
Width
Height
end
properties (Dependent)
Area
end
methods
function obj = Rectangle(w,h)
obj.Width = w;
obj.Height = h;
end
function a = get.Area(obj)
a = obj.Width * obj.Height;
end
end
end
obj = Rectangle(4,5);
disp(obj.Area)Attempts:
2 left
💡 Hint
Dependent properties compute their value on access.
✗ Incorrect
The dependent property Area calculates Width * Height, which is 4 * 5 = 20.
❓ Predict Output
advancedError type when accessing private property
What error occurs when running this code?
MATLAB
classdef Secret
properties (Access = private)
Data = 42;
end
methods
function val = getData(obj)
val = obj.Data;
end
end
end
s = Secret();
disp(s.Data);Attempts:
2 left
💡 Hint
Private properties cannot be accessed directly from outside the class.
✗ Incorrect
Accessing a private property directly from outside the class causes an error saying no such property is accessible.
🧠 Conceptual
expertNumber of items in property after method call
Consider this MATLAB class that stores names in a property. After running the code below, how many names are stored in the
Names property?MATLAB
classdef NameList
properties
Names = {};
end
methods
function obj = addName(obj, newName)
obj.Names{end+1} = newName;
end
end
end
list = NameList();
list = list.addName('Alice');
list = list.addName('Bob');
list = list.addName('Charlie');
disp(length(list.Names))Attempts:
2 left
💡 Hint
Each call to addName adds one name to the cell array.
✗ Incorrect
The addName method appends a new name to the cell array Names. After three calls, there are 3 names stored.
