Introduction to Object-Oriented Programming in MATLAB
MATLAB supports object-oriented programming (OOP) through classdef files, which let you bundle related data (properties) and behavior (methods) into a single reusable unit called a class. Instead of scattering separate arrays and standalone functions across a script, OOP groups everything a concept needs — state and the operations on that state — into one class definition, making code easier to reuse, extend, and reason about as programs grow beyond a handful of scripts.
Cricket analogy: Think of a cricket team roster class - each Player object bundles properties (name, average, role) with methods (bat(), bowl()) instead of scattering separate arrays for names and stats like old procedural scorecards.
Defining Classes with classdef
Every MATLAB class lives in a file named after the class, starting with classdef ClassName, followed by a properties block declaring the object's data fields and a methods block defining functions that operate on those fields, including a constructor with the same name as the class. Method calls use standard dot notation (obj.methodName(args)), and the constructor typically initializes property values and performs any validation needed before the object is considered ready to use.
Cricket analogy: Declaring properties for battingAverage and methods for calculateStrikeRate in a classdef file is like the BCCI's official scorecard template that fixes which fields and calculations every match report must contain.
classdef Player
properties
Name
BattingAverage = 0
end
methods
function obj = Player(name, avg)
obj.Name = name;
obj.BattingAverage = avg;
end
function rate = strikeRate(obj, runs, balls)
rate = (runs / balls) * 100;
end
end
end
% Usage
p = Player('Kohli', 58.7);
sr = p.strikeRate(82, 60);Constructors, Handle vs Value Classes
By default, MATLAB classes have value semantics: assigning an object to a new variable creates an independent copy, and modifying the copy leaves the original untouched — just like assigning a numeric array. Subclassing the built-in handle class (classdef MyClass < handle) switches to reference semantics, where multiple variables can point to the same underlying object, and a mutation through any one of them is visible through all the others, which is essential for shared, stateful resources.
Cricket analogy: A value-class Scorecard object copied when passed to a function is like handing a teammate a photocopy of the scoreboard — their edits don't change the original, unlike a handle-class Scoreboard that behaves like a shared live scoreboard everyone edits in real time.
A common gotcha: if a function modifies a value-class object's property and doesn't explicitly return and reassign the modified object (obj = obj.setValue(x)), the caller's copy is unaffected. Handle classes avoid this by mutating the shared object directly, but that convenience comes with the risk of unintended side effects if multiple parts of your program hold references you forgot were shared.
Inheritance and Polymorphism
A subclass extends a superclass with the syntax classdef Sub < Super, inheriting all its properties and methods while being able to override any method by redefining it with the same name and signature. Inside an overriding method, you can still invoke the superclass's original implementation using the methodName@Superclass(obj, ...) syntax, which lets you extend rather than completely replace inherited behavior — a common pattern for adding specialized logic on top of shared base functionality.
Cricket analogy: An AllRounder class extending Player and overriding the bowl() method while calling bowl@Player(obj) first is like a player training under the base coaching curriculum, then adding specialized spin-bowling drills on top.
If a superclass constructor requires input arguments, every subclass constructor must explicitly call it first with obj = obj@Superclass(args) before the object is considered fully constructed — omitting this call, or calling it after setting subclass properties, produces confusing errors or objects left in an inconsistent state.
Encapsulation with Access Attributes
Properties and methods can be marked with access attributes such as Access = public (the default), Access = protected (visible to the class and its subclasses only), or Access = private (visible only within the class itself), letting you control exactly which code is allowed to read or modify internal state directly. A common pattern pairs a private property with public get/set methods that validate or transform values on every read or write, preventing external code from putting an object into an invalid state.
Cricket analogy: Marking a Player's injuryHistory property as Access = private protects sensitive medical data from other classes, similar to how only the team physio, not opposing captains, can view a player's injury file.
- MATLAB classes are defined in classdef files with a properties block and a methods block.
- Value classes copy on assignment; handle classes (subclassing
handle) share references so mutations propagate everywhere the object is referenced. - Subclasses extend a superclass with
classdef Sub < Superand can override methods while still calling the superclass version withmethod@Super(obj, ...). - Access attributes like
Access = privateandAccess = protectedcontrol which code can read or modify a property directly. - Get and set methods (property access methods) let you validate or transform data whenever a property is read or written.
- Constructors share the class name and typically call
obj = obj@Superclass(args)first when subclassing.
Practice what you learned
1. In a MATLAB classdef file, what determines whether an object exhibits value semantics or handle semantics?
2. What is the correct way for an overriding method to call its superclass's implementation of the same method?
3. Which access attribute would you use so that a property can only be modified by methods of the class itself, not by subclasses or external code?
4. When you assign a value-class object to a new variable and modify the new variable, what happens to the original?
5. What must a subclass constructor typically do first when the superclass constructor requires arguments?
Was this page helpful?
You May Also Like
MATLAB Toolboxes Overview
A tour of MATLAB's major add-on toolboxes — what they add on top of base MATLAB, when to reach for each one, and how to check what's installed and licensed.
Debugging and Profiling MATLAB Code
Practical techniques for finding correctness bugs with MATLAB's interactive debugger and finding performance bottlenecks with the Profiler.
MATLAB and Python Interoperability
How to call Python libraries from MATLAB, call MATLAB functions from Python, and package MATLAB code as standalone Python modules.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics