MATLAB Language Constructors


A constructor is a special method in a class that is called when an instance of an object is created. It is a regular MATLAB function that accepts input parameters but it also must follow certain rules.

Constructors are not required as MATLAB creates a default one. In practice, however, this is a place to define a state of an object. For example, properties can be restricted by specifying attributes. Then, a constructor can initalize such properties by default or user defined values which in fact can sent by input parameters of a constructor.

Calling a constructor of a simple class

This is a simple class Person.

classdef Person
        function obj = Person(name,surname,address)
   = name;
            obj.surname = surname;
            obj.address = address;

The name of a constructor is the same the name of a class. Consequently, constructors are called by the name of its class. A class Person can be created as follows:

>> p = Person('John','Smith','London')
p = 
  Person with properties:

       name: 'John'
    surname: 'Smith'
    address: 'London'

Calling a constructor of a child class

Classes can be inherited from parent classes if the share common properties or methods. When a class is inherited from another, it is likely that a constructor of a parent class has to be called.

A class Member inherits from a class Person because Member uses the same properties as the class Person but it also adds payment to its definition.

classdef Member < Person

        function obj = Member(name,surname,address,payment)
            obj = obj@Person(name,surname,address);
            obj.payment = payment;

Similarly to the class Person, Member is created by calling its constructor:

>> m = Member('Adam','Woodcock','Manchester',20)
m = 
  Member with properties:

    payment: 20
       name: 'Adam'
    surname: 'Woodcock'
    address: 'Manchester'

A constructor of Person requires three input parameters. Member must respect this fact and therefore call a constructor of the class Person with three parameters. It is fulfilled by the line:

obj = obj@Person(name,surname,address);

The example above shows the case when a child class needs information for its parent class. This is why a constructor of Member requires four parameters: three for its parent class and one for itself.