MATLAB CLASSES getter and setters

前端 未结 2 1104
长情又很酷
长情又很酷 2021-01-06 02:23

I come from a Java background. I am having issues with classes in Matlab particularly getters and setters. getting a message saying conflict between handle and value class I

2条回答
  •  Happy的楠姐
    2021-01-06 02:37

    Implementation

    Since your class is currently a subclass of the default Value class, your setters need to return the modified object:

    function obj = set.name(obj,name)
    end
    function obj = set.age(obj,age)
    end
    

    From the documention: "If you pass [a value class] to a function, the function must return the modified object." And in particular: "In value classes, methods ... that modify the object must return a modified object to copy over the existing object variable".


    Handle classes (classdef Person < handle) do not need to return the modified object (like returning void):

    function [] = set.name(obj,name)
    end
    function [] = set.age(obj,age)
    end
    

    Value vs. Handle

    Going a bit deeper, the difference between a Value class and a Handle class lies mostly in assignment:

    • Assigning a Value class instance to a variable creates a copy of that class.
    • Assigning a Handle class instance to a variable create a reference (alias) to that instance.

    The Mathworks has a good rundown on this topic. To paraphrase their illustration, the behavior of a Value class is

    % p  is an instance of Polynomial
    p = Polynomial(); 
    % p2 is also an instance of Polynomial with p's state at assignment
    p2 = p;
    

    and of a Handle class is

    % db is an instance of Database
    db = Database();
    % db2 is a reference to the db instance
    db2 = db;
    

提交回复
热议问题