matlab类的结构:
% 类名:Person
classdef Person
properties
% 属性 简单来说就是这个类有包括哪些
Name
Age
Add
end
% 方法,也就是这个类能执行什么操作
methods
% 实例化对象
function obj = Person(name, age)
obj.Name = name;
obj.Age = age;
obj.Add = 5 + age;
end
% 打印人名单
function displayInfo(obj)
% 这里区分 <handle
obj.Add = obj.Add + obj.Age;
disp(['Name: ' obj.Name]);
disp(['Age: ' num2str(obj.Age)]);
disp(['Add_last: ' num2str(obj.Add)]);
end
end
end
输入: 小张 19 调用Add得到24
然而:
当调用函数displayInfo()时,Add_last=43(这是由于19+24=43)
因此,此时obj.Add==43(这一点从打印结果Add_last=43可以看出来)
但:
实例化的s1中可以看到,Add = 24 并没有变为43,这是由于displayInfo没有返回值导致的,为了解决这个问题,可以继承父类 <handle
类的继承
% 再定义一个Teacher类,继承Person类的属性
classdef Teacher < Person
% Teacher类所特有的属性为: Title、Id、Money
properties
Title
Id
Money
end
methods
% 对象实例化
function obj = Teacher(name, age, title,id)
% 继承父类的name属性和age属性
obj = obj@Person(name, age);
obj.Title = title;
obj.Id = id;
end
function displayInfo(obj)
obj.Money = obj.Id+obj.Age;
disp('Teacher Information:');
disp(['Name: ' obj.Name]);
disp(['Age: ' num2str(obj.Age)]);
disp(['Title: ' obj.Title]);
end
end
end
运行结果:
属性说明:
1.public
classdef Student
properties
Name % 共有属性
Age % 共有属性
end
methods
function obj = Student(name, age)
obj.Name = name; % 可以在类的外部访问和赋值
obj.Age = age; % 可以在类的外部访问和赋值
end
end
end
2.private
classdef Student
properties (Access = private)
Name % 私有属性
Age % 私有属性
end
methods
function obj = Student(name, age)
obj.Name = name; % 只能在类的内部访问和赋值
obj.Age = age; % 只能在类的内部访问和赋值
end
end
end
3.Constant
properties (Constant)
Gravity = 9.81; % 常量属性
end
4.只读
classdef ReadOnlyExample
properties (SetAccess = immutable) % 只读
ConstantValue
end
methods
function obj = ReadOnlyExample(value)
obj.ConstantValue = value; % 只能在构造函数中赋值
end
function tryToUpdate(obj, newValue)
obj.ConstantValue = newValue; % 试图修改只读属性会产生错误
end
end
end
5.你可以使用 Access
属性将属性设置为受保护的,这意味着这些属性只能在类的方法和子类中被访问
classdef ProtectedPropertyExample
properties (Access = protected)% 受保护属性
ProtectedValue
end
methods
function obj = ProtectedPropertyExample(value)
obj.ProtectedValue = value; % 可以在类的方法中访问和赋值
end
function displayProtectedValue(obj)
disp(['Protected Value: ' num2str(obj.ProtectedValue)]); % 可以在类的方法中访问
end
end
end
% 创建对象并尝试访问受保护属性
example = ProtectedPropertyExample(5);
example.displayProtectedValue(); % 可以访问受保护属性
example.ProtectedValue; % 试图直接访问受保护属性会产生错误