Consider the following MATLAB classes and script. What is the output when the script runs?
classdef Animal
methods
function sound(obj)
disp('Some generic animal sound')
end
end
end
classdef Dog < Animal
methods
function sound(obj)
disp('Bark')
end
end
end
% Script
myPet = Dog();
myPet.sound();Think about which class's sound method is called when you create a Dog object.
The Dog class overrides the sound method of Animal. So calling sound on a Dog object prints 'Bark'.
What is the output of this MATLAB code?
classdef Vehicle
methods
function start(obj)
disp('Vehicle started')
end
end
end
classdef Car < Vehicle
methods
function start(obj)
disp('Car engine warming up')
start@Vehicle(obj);
end
end
end
myCar = Car();
myCar.start();Look at how the superclass method is called inside the subclass method.
The Car class's start method first displays 'Car engine warming up' then explicitly calls the Vehicle class's start method, which displays 'Vehicle started'.
What error does this MATLAB code produce when run?
classdef Parent
properties
Name
end
methods
function obj = Parent(name)
obj.Name = name;
end
end
end
classdef Child < Parent
methods
function obj = Child(name)
obj.Name = name;
end
end
end
c = Child('Alice');Think about how constructors work in inheritance in MATLAB.
The Child constructor does not call the Parent constructor explicitly. MATLAB requires calling the superclass constructor to properly initialize inherited properties.
Which of the following MATLAB subclass constructors correctly calls the superclass constructor?
Look for the correct syntax to call superclass constructor in MATLAB subclass constructor.
Option D uses the correct syntax obj = obj@Parent(name); to call the superclass constructor. Other options are either invalid syntax or do not assign the object properly.
Given these MATLAB classes, how many methods does an object of class Manager have access to?
classdef Employee
methods
function work(obj)
disp('Working')
end
function report(obj)
disp('Reporting')
end
end
end
classdef Manager < Employee
methods
function manage(obj)
disp('Managing')
end
end
end
m = Manager();Count all methods defined in Manager and its superclass Employee.
The Manager class inherits work and report from Employee and defines its own method manage. So total methods accessible are 3.
