Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to define a constructor method named MyClass.
MATLAB
classdef MyClass
methods
function obj = [1]()
obj.value = 0;
end
end
endAttempts:
3 left
💡 Hint
Common Mistakes
Using a different function name than the class name for the constructor.
Forgetting to define the constructor as a method inside the class.
✗ Incorrect
In MATLAB, the constructor method must have the same name as the class, here 'MyClass'.
2fill in blank
mediumComplete the constructor to accept an input argument val and assign it to the property value.
MATLAB
classdef MyClass
properties
value
end
methods
function obj = MyClass([1])
if nargin > 0
obj.value = val;
else
obj.value = 0;
end
end
end
endAttempts:
3 left
💡 Hint
Common Mistakes
Using a different input argument name than the one assigned to the property.
Not including any input argument in the constructor.
✗ Incorrect
The constructor takes 'val' as input to assign it to the property 'value'.
3fill in blank
hardFix the error in the constructor method to properly initialize the object.
MATLAB
classdef MyClass
properties
value
end
methods
function obj = MyClass(val)
if nargin == 0
obj.value = 0;
else
obj.[1] = val;
end
end
end
endAttempts:
3 left
💡 Hint
Common Mistakes
Assigning to obj.val instead of obj.value.
Using parentheses after the property name.
✗ Incorrect
The property 'value' must be assigned the input 'val', so use obj.value = val.
4fill in blank
hardFill both blanks to create a constructor that sets value and a new property name.
MATLAB
classdef MyClass
properties
value
name
end
methods
function obj = MyClass([1], [2])
if nargin == 2
obj.value = val;
obj.name = nm;
else
obj.value = 0;
obj.name = '';
end
end
end
endAttempts:
3 left
💡 Hint
Common Mistakes
Using property names as input argument names.
Mixing up the order of input arguments.
✗ Incorrect
The constructor takes two inputs: 'val' for value and 'nm' for name.
5fill in blank
hardFill all three blanks to create a constructor that sets value, name, and active properties.
MATLAB
classdef MyClass
properties
value
name
active
end
methods
function obj = MyClass([1], [2], [3])
if nargin == 3
obj.value = val;
obj.name = nm;
obj.active = act;
else
obj.value = 0;
obj.name = '';
obj.active = false;
end
end
end
endAttempts:
3 left
💡 Hint
Common Mistakes
Using property names as input argument names.
Forgetting to include all three input arguments.
✗ Incorrect
The constructor inputs are 'val', 'nm', and 'act' to set the properties value, name, and active.
