Scilab Website | Contribute with GitLab | Scilab Community | ATOMS toolboxes
Scilab Online Help
2027.0.0 - Français


Classdef and objects

Classdef and objects

Description

Define classes and objects in Scilab scripts

Definition

Classdef are used to define a set of properties and/or methods that work together. Properties are like variables and methods like functions.

classdef <classname> < <superclass> & <superclass>
    properties (<modifiers>)
        var1 = []
    end

    methods (<modifiers>)
        function <classname>(args...) // constructor
            ...
        end

        function rets=func1(args...)
            ...
        end

        func2 = externalfunc
    end

    enumeration
        enum1(args...)
        enum2(args...)
        enum3(args...)
    end
end

Classes are defined by :

  • Name: it will be used to use class

  • Superclass: names of superclass from which it derives

  • Properties: variables used inside or outside class to store data

  • Methods: functions to do some operations

  • Enumeration: Specific instances of class

  • Properties and Methods can have some modifiers to change their visibility or behavior:

    • Private: elements can be used only inside methods of this class. (Public/Protected/Private are exclusive)

    • Protected: elements can be used inside methods of this class and its children (inheritance). (Public/Protected/Private are exclusive)

    • Public (default): elements can be used outside and inside of this class. (Public/Protected/Private are exclusive)

    • Static: elements are shared across all instances of this class and can be accessed via the class name (MyClass.prop) or via an instance (obj.prop). Static methods do not receive this (see "Static members" below).

inheritance

Classes can derive from one or multiple classes. (with &) In this case, elements of the parent classes can be used in this class (depends of the modifiers)

classdef <classname> < <superclass> & <superclass>
end

The constructor of a direct parent is called by its name, without output, in the constructor of the derived class: A(args) initializes the A part of this (x = A(args) builds another object). This call is only allowed in the constructor of a direct subclass.

The constructor of a parent that is not called this way is called implicitly, without argument, before the constructor of the derived class, and also when the derived class has no constructor. In a diamond inheritance, a common parent is initialized once. A parent constructor that needs arguments must be called explicitly.

classdef Shape
    properties
        name = ""
    end
    methods
        function Shape(n)
            this.name = n;
        end
    end
end

classdef Circle < Shape
    properties
        r = 0
    end
    methods
        function Circle(r)
            Shape("circle");    // initialization of the Shape part
            this.r = r;
        end
    end
end

c = Circle(2);
c.name      // "circle"

Properties

Define properties of class. Visibility modifier can be private, protected or public. A default value can be added to initialize variable during instantiation (default []).

As in an arguments block, a property can declare its size, its type and validation functions, checked on the default value and on each assignment. The default value, written in the class, is expanded, transposed or converted if needed (n int8 = 1). An assigned value is not converted: it must already have the declared type and size, otherwise an error is raised. What is read from a property is what was assigned to it. The type can be a classdef name: the value must be an object of this class or of a derived one. Parameters of validation functions can be the property itself, constants, and static properties of classes (MyClass.MAX), evaluated at each check. They can not use the object (this) nor its other properties: the check of a property would not follow their changes. Such a constraint is checked by a method setting the property, whose arguments block can use this.

Properties can also be declared Static. Static properties are shared across all instances and can be accessed via the class name or via any instance.

classdef <classname>
    properties (<modifier>)
        var1 = []
        var2 (1,1) double {mustBePositive} = 1
        var3 {mustBeInRange(var3, 0, 10)} = 5
    end

    properties (Static)
        sharedVar = 0
    end
end

Methods

Define methods of class. Visibility modifier can be private, protected or public. In methods this must be used to access to properties or methods of the object.

Methods can also be declared Static. Static methods do not receive this and can be called via the class name (MyClass.method()) or via an instance (obj.method()). In a static method, static members of the class are accessed via the class name (MyClass.member), whatever their visibility.

classdef <classname>
    methods (<modifier>)
        function rets=func(args...)
            this.var1 = 12;
        end

        func2 = externalfunc
    end

    methods (Static)
        function r=helper(x)
            r = x * 2;
        end
    end
end

Note: externalfunc can be a macro or a C/C++ gateway.

In C/C++ gateway, use symbol::Context::getInstance()->getCurrentObject() to get this (the classdef for a static method) and getCurrentClass() to get the class defining the method.

Static members

A static property holds a single value shared by the class, all its instances and its derived classes. A static method is not bound to an instance: it does not receive this.

  • Outside the class: MyClass.prop, MyClass.method(), or through any instance: obj.prop, obj.method(). Private and protected static members are not accessible.

  • In an instance method: MyClass.prop or this.prop, both refer to the same shared value. The class name makes clear that the value is shared.

  • In a static method: there is no this, always use the class name (MyClass.prop, MyClass.method()), whatever the visibility of the member. this.prop raises "Undefined variable: this".

  • Instance properties do not exist in a static method: to work on an object, pass it as argument (function r = f(obj)). As the method belongs to the class, private and protected members of obj are accessible.

  • A derived class shares the static members of its parents: Derived.prop and Base.prop are the same value.

  • The constructor is always an instance method: declare it in a methods block without the Static modifier and use this to initialize the object. A constructor declared in a methods (Static) block raises an error at the definition of the class.

classdef Account
    properties (Static, Private)
        count = 0       // shared: number of accounts
    end

    properties (Private)
        balance = 0     // one value per instance
    end

    methods
        function Account(b)                 // constructor: instance method
            this.balance = b;               // instance property: this
            Account.count = Account.count + 1;  // static property: class name
        end
    end

    methods (Static)
        function r=total()
            r = Account.count;              // no this in a static method
        end

        function r=balanceOf(acc)
            r = acc.balance;                // an instance is given as argument
        end
    end
end

a1 = Account(100);
a2 = Account(50);
Account.total()         // 2
a1.total()              // 2, same value through an instance
Account.balanceOf(a2)   // 50
// Account.count        // error: private static property

Enumeration

Define enumeration of class. They are specific instances of the class associated to a name.

classdef Color
    enumeration
        RED     (args...)
        GREEN   (args...)
        BLUE    (args...)
    end
end

//usage
Color.RED
Color.GREEN
Color.BLUE

Overloads

Overloads will be called for undefined operations or function calls. (overloading)

There is 2 forms:

  • External: defining an overload function %type1_operator_type2 for operators (standard overload way in Scilab)

    Or %type_function for functions

  • Internal: using methods declaration in classdef

    For functions, define a method with the same name (ex: disp in following example)

    There is special functions called by internal mecanism like:

    • saveobj: call when saving an object to serialize data.

      prototype: function data=saveobj(), end

      You have to return a native scilab variable (struct, list, ...) except objects that contains all data you want to save.

    • loadobj: called when object is restore by load function.

      prototype: function loadobj(data), end

      data is the variable returned by saveobj.

    • delete: called when object is cleared

      prototype: function delete(), end

    For operators following the lookup table :

    Operations Methods to define Operations Methods to define Operations Methods to define Operations Methods to define
    a + b plus(a, b) +a uplus(a) a - b minus(a, b) -a uminus(a)
    a * b mtimes(a, b) a / b mrdivide(a, b) a \ b mldivide(a, b) a ^ b mpower(a, b)
    a .* b times(a, b) a ./ b rdivide(a, b) a .\ b ldivide(a, b) a .^ b power(a, b)
    a .*. b kron(a, b) a ./. b rkron(a, b) a .\. b lkron(a, b)
    a *. b controltimes(a, b) a /. b controlrdivide(a, b) a \. b controlldivide(a, b)
    Comparisions Methods to define Comparisions Methods to define
    a == b eq(a, b) a <> b ne(a, b)
    a < b lt(a, b) a <= b le(a, b)
    a > b gt(a, b) a >= b ge(a, b)
    a & b and(a, b) a | b or(a, b)
    a && b shortand(a, b) a || b shortor(a, b)
    Operations Methods to define Operations Methods to define Operations Methods to define
    ~a not(a) a' ctranspose(a) a.' transpose(a)

    Matrix manipulations Methods to define Matrix manipulations Methods to define
    [a b] horzcat(a, b) [a;b] vertcat(a, b)
    a(i1, i2, ...) extract(i1, i2, ...) a(i1, i2, ...) = b insert(i1, i2, ..., b)

    for the most part of overload, you can definie a specific one for a identitified type.

    ex: insert_s (insertion of a double in the object).

    generic one will be used if specific one does not exist.

    Search order is: specific (insert_s), generic (insert), scilab standard (%type1_i_type2)

    For an operator between two operands, the methods of the left operand are searched first, then those of the right operand. && and || use the and and or methods, as & and |.

classdef Matrix
    properties
        value = []
    end
    methods
        function Matrix(v)
            this.value = v;
        end

        function r=plus(a, b) //generic overload for operation +
            if isa(a, "Matrix") & isa(b, "Matrix") then
                r = Matrix(a.value + b.value);
            else
                error(sprintf("Operation + not defined for %s and %s.\n", typeof(a), typeof(b)));
            end
        end

        function r=plus_s(a, b) //overload for Matrix + double or double + Matrix
            if isa(a, "Matrix") then
                r = Matrix(a.value + b);
            else
                r = Matrix(a + b.value);
            end
        end

        function r=plus_i(a, b) //overload for Matrix + int or int + Matrix
            if isa(a, "Matrix") then
                r = Matrix(a.value + double(b));
            else
                r = Matrix(double(a) + b.value);
            end
        end

        function disp()
            disp(this.value);
        end
    end
end

a = Matrix([1 2 3 4]);
b = Matrix([4 3 2 1]);
a + b
a + 10
10 + b
a + int8(10)
int8(10) + b

Examples

Usage of enumeration:

classdef Color
    properties
        R
        G
        B
    end

    methods
        function Color(varargin)
            s = size(varargin);

            select (s)
            case 1
                c = varargin(1);
                [_, _, _, colors] = regexp(c, "/([0-9A-Fa-f]{1,2})([0-9A-Fa-f]{1,2})([0-9A-Fa-f]{1,2})/");

                colors = hex2dec(part(colors + colors, 1:2));
                this.R = colors(1);
                this.G = colors(2);
                this.B = colors(3);
            case 3
                this.R = modulo(varargin(1), 256);
                this.G = modulo(varargin(2), 256);
                this.B = modulo(varargin(3), 256);
            end
        end

        function disp()
            printf("Color: #%02x%02x%02x\n", this.R, this.G, this.B);
        end
    end

    enumeration
        BLACK     (  0,   0,   0)
        BLUE      (  0,   0, 255)
        GREEN     (  0, 255,   0)
        CYAN      (  0, 255, 255)
        RED       (255,   0,   0)
        MAGENTA   (255,   0, 255)
        YELLOW    (255, 255,   0)
        WHITE     (255, 255, 255)
   end
end

red = Color.RED
gray1 = Color(128, 128, 128)
gray2 = Color("#808080")

Usage of static properties and methods:

classdef Counter
    properties (Static)
        count = 0
    end

    methods
        function Counter()
            Counter.count = Counter.count + 1;
        end

        function delete()
            Counter.count = Counter.count - 1;
        end

        function disp()
            printf("Instance of Counter (total: %d)\n", Counter.count);
        end
    end

    methods (Static)
        function r=getCount()
            r = Counter.count;
        end

        function reset()
            Counter.count = 0;
        end
    end
end

// access static property via class name
Counter.count

// create instances, count increases
c1 = Counter()
c2 = Counter()

// access static property via instance
c1.count

// call static method via class name
Counter.getCount()

// call static method via instance
c2.getCount()

// clear instances, count decreases
clear c1;
Counter.count

// reset via static method
Counter.reset()
Counter.count

See also

  • overloading — display, functions and operators overloading capabilities
  • properties — Get accessible properties of a classdef or an object
  • methods — Get accessible methods of a classdef or an object
  • enumeration — Get enumeration of a classdef or an object

History

VersionDescription
2026.0.0

classdef introduction.

2026.1.0

Static modifier added for properties and methods.

2027.0.0

Size, type and validation functions of properties are applied. Default values are converted to the declared type and size, assigned values are not.

Change of behavior: the constructor of a parent that is not called by the constructor of the derived class (or when the derived class has no constructor) is now called implicitly, without argument. A parent constructor that needs arguments must be called explicitly, and a parent with a private constructor can not be derived anymore. Calling a parent constructor A() is only allowed in the constructor of a direct subclass (it reinitialized the object from any method).

Change of behavior: protected members are visible to all derived classes (they were visible to direct subclasses only), and a method can access private members of other instances of its class.

A constructor declared in a methods (Static) block is an error.

Report an issue
<< boolean types functions >>

Copyright (c) 2022-2026 (Dassault Systèmes S.E.)
Copyright (c) 2017-2022 (ESI Group)
Copyright (c) 2011-2017 (Scilab Enterprises)
Copyright (c) 1989-2012 (INRIA)
Copyright (c) 1989-2007 (ENPC)
with contributors
Last updated:
Thu Oct 15 11:13:59 CEST 2026